Cannot get my routes that have been defined

Issue

I am trying to add routes to my expressjs project. I am trying to make it so that when I go to ‘localhost:9000/users’ it returns ‘User List’. Currently it shows ,’Cannot GET /users’. I have tried putting the code in users.js into server.js and replaced the router with app but that did not work.
routes/users.js:

const express = require("express")
const router = express.Router()

router.get("/", (req, res) => {
  res.send("User List")
})

router.get("/new", (req, res) => {
  res.render("users/new")
})

module.exports = router;

server.js:

const express = require('express')
const app = express()
const port = 9000
const userRouter = require("routes/users")
app.set('view engine', 'ejs')

app.get('/', (req, res) => {
  res.render('index', {username: 'xpress'})
})

app.use("/users", userRouter)

app.listen(port, () => {
  console.log(`App listening at port ${port}`)
})

Solution

I copy your code and only modify

const userRouter = require("routes/users")

to

const userRouter = require("./routes/users")

and I have the desired output

enter image description here

You should use "./" to refer to your files. Otherwise, Node.js will search for package "routes/users" in built-in packages, globally-installed packages, and in node_modules folder. Of course, it doesn’t available in these places.

Answered By – Đăng Khoa Đinh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published