Routes are not working in my express js app

Routes are not working in my express js app

Problem Description:

I was working on a personal express project. I’ve created two files one server file and other restaurants.route.js to sepearate routes and server code. But I’m not able trigger the home route from local host. Moreover no console error is showing only the 404 page error.

server.js code:

import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";


// initialising express app
const app = express();

// applying middlewears
app.use(cors());
app.use(express.json());
app.use("api/v1/restaurants", restaurants);
app.use("*", (req, res) => res.status(404).json({error: "not found"}));

export default app;

restaurants.route.js:

import express from "express";

// express router
const router = express.Router();

router.route("/")
  .get((req, res) => {
    res.send("Hello World");
});`enter code here`

export default router;

Solution – 1

It looks like you might be missing the leading forward slash (/) in the path you’re using to mount the restaurants router in your server.js file. When you use the app.use() method to mount a router, the path you specify should start with a forward slash.

So instead of this:

app.use("api/v1/restaurants", restaurants);

Try this:

app.use("/api/v1/restaurants", restaurants);
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject