skip to Main Content

I am struggling with some Express routs that behave differently even though the code to execute is the same.

I want a client application to call the API as follows:

async search(){

      const query = this.$refs.searchInput.value;
      console.log(query);

      const addressToFetch = "/api/budget/search?q=" + query;
      await fetch(addressToFetch)
        .then((response) => response.json())
        .then((response) => {
          console.log(response);
        });
    }

Where the value of query is taken from the following input HTML tag:

              <div class="input-group row text-right">
                <!--flex-nowrap-->
                <div class="col">
                  <input
                    type="text"
                    id="searchInput"
                    name="search"
                    placeholder="Search"
                    ref="searchInput"
                  />
                  <button
                    type="button"
                    class="btn btn-primary btn-search btn-filter"
                    @click="search"
                  >
                    <i class="fa fa-search" aria-hidden="true"></i>
                  </button>

                  <button
                    type="button"
                    class="btn btn-danger"
                    v-if="filteredResults"
                    @click="getExpenses"
                  >
                    Undo
                  </button>
                </div>
              </div>

The server-side application handles the request as follows:

app.get("/api/budget/search", verify, async (req, res) => {
  console.log(req.query.q);
  const users = await db
    .collection("users")
    .find({ username: { $regex: req.query.q } })
    .toArray();
  users.forEach((user) => {
    delete user.password;
  });

  res.json(users);
});

After authentication, this function returns [] and not even server-side logs are printed. Checking with Postman, I can see that the response is 200 OK anyway. I created a different route for testing purposes with the same code inside. It turns out that the new route gives different (good) results:

app.get("/api/users/search", verify, async (req, res) => {
  console.log(req.query.q);
  const users = await db
    .collection("users")
    .find({ username: { $regex: req.query.q } })
    .toArray();
  users.forEach((user) => {
    delete user.password;
  });

  res.json(users);
});

I leave you all the routes to see if there are any problems with it:

const express = require("express");
const fs = require("fs/promises");
const session = require("express-session");
const { MongoClient } = require("mongodb");
const exp = require("constants");
const uri = "mongodb://mongohost";
const app = express();

const client = new MongoClient(uri);
let db = null;

app.use(express.static(`${__dirname}/public`));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(
  session({
    secret: "segreto",
    resave: false,
  })
);

function verify(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.status(403);
  }
}

app.post("/api/auth/signup", async (req, res) => {});

app.post("/api/auth/signin", async (req, res) => {...});

app.get("/api/budget/whoami", verify, (req, res) => {...});

app.get("/api/budget", verify, async (req, res) => {...});

app.get("/api/budget/:year", verify, async (req, res) => {...});

app.get("/api/budget/:year/:month", verify, async (req, res) => {...});

app.get("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.post("/api/budget/:year/:month", verify, async (req, res) => {...});

app.put("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.delete("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.get("/api/balance", verify, async (req, res) => {...});

app.get("/api/balance/:id", verify, async (req, res) => {...});

app.get("/api/budget/search", verify, async (req, res) => {...});


app.get("/api/users/search", verify, async (req, res) => {...});

app.listen(3000, async () => {
  await client.connect();
  db = client.db("balanceApp");
});

I don’t get the problem with the first route, is there anything I can do to fix the problem? Thank you very much for your patience.

2

Answers


  1. You have a route /api/budget/:year which matches /api/budget/search, it must have fallen into this handler instead

    Login or Signup to reply.
  2. If your Express route is not returning any value and you suspect that the function is not being executed, there are several things you can check and steps you can take to troubleshoot the issue. Here are some common suggestions:

    1. Check Your Route Definition:
      Double-check the definition of your Express route. Ensure that you have correctly defined the HTTP method (e.g., GET, POST, PUT, DELETE) and the correct path.
    2. Check Middleware:
      If you have middleware functions in your route, make sure they are properly configured and not preventing the route handler from being executed.
    3. Check for Errors:
      Make sure that there are no errors in your route handler function. Log any errors to the console or use a debugger to identify potential issues.
    4. Check for Route Execution:
      Add console.log or debugger statements inside your route handler to see if the function is being executed. This can help you determine if the issue lies within the handler itself.
    5. Check Route Order:
      Ensure that your route is defined in the correct order. Express routes are matched in the order they are defined, so make sure that there are no conflicting routes defined before the one you are troubleshooting.
    6. Check Server Startup:
      Make sure that your Express server is running and listening for incoming requests. Check the console for any startup errors.
    7. Use a Minimal Example:
      If the issue persists, create a minimal example with just the necessary code to identify where the problem might be occurring. Gradually add complexity until the issue reappears.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search