Home > Net >  Unable to set routes for my API in nodejs
Unable to set routes for my API in nodejs

Time:10-03

Routes are not showing up like /courses.

This is the code in my app.js

const express = require('express');
const connectDB = require('./config/db');

const app = express();

const courses = require("./routes/api/courses");


//connectDB
connectDB();

app.get('/', (req, res) => res.send('Hello world!'));


//using routes
app.use('api/courses', courses);

const port = process.env.PORT || 8082;

app.listen(port, () => console.log(`Server running on port ${port}`));

And this is code in routes/api/courses

const express = require('express');
const router = express.Router();

const course = require("../../models/Course");

// @route GET api/courses
// @description Get all courses
// @access Public

router.get('/courses',(req,res)=>{
  res.send('Courses are connected!');
})

module.exports = router;

It it not showing up in /courses in localhost/courses. output there is: Cannot get /courses

I am a beginner in nodejs express.

CodePudding user response:

You say that you're expecting your server to respond to:

http://localhost/courses

but you show code that defines a route for:

http://localhost/api/courses/courses

When you do this:

app.use('api/courses', courses);

You're telling Express to send any request to the courses router whose path starts with /api/courses. So, right away, nothing will get sent to that route unless it starts with /api/courses. That already rules out http://localhost/courses.

Then, in your courses router, you define this:

router.get('/courses',(req,res)=>{..}

That means you're defining a route for:

http://localhost/api/courses/courses

The first /api/courses comes from the app.use() that registers the router. The second /courses comes from this route definition.


If you want it to respond to:

http://localhost/courses

Then, you should change this:

app.use('api/courses', courses);

to this:

app.use(courses);

That will send all possible paths to the courses router where it's check for /courses will result in a top level route handler for

http://localhost/courses
  • Related