Home > OS >  Cannot get my routes that have been defined
Cannot get my routes that have been defined

Time:08-11

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}`)
})

CodePudding user response:

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.

  • Related