Home > Software engineering >  Express routes working with url params but not with specific sub routes
Express routes working with url params but not with specific sub routes

Time:04-01

I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:

Post.js

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

const { ObjectID } = require('mongodb')
const { mongoose } = require('../db/mongoose');
// const PostModel  = require("../models/Post");

// const Post = PostModel(mongoose);
const {Post} = require("../models/Post.js")

const log = console.log;

router.post('/', (req, res) => {

    const post = new Post({
        postName: req.body.postName,
        postDescription: req.body.postDescription,
    })

    post.save().then((result) => {
        res.send(result)
    }).catch((error) => {
        log(error)
        if (isMongoError(error)) {
            res.status(500).send('Internal server error')
        } else {
            res.status(400).send('Bad Request') 
        }
    })

})

router.get('/:id', (req, res) => {
    const id = req.params.id

    Post.findById(id).then((post) => {
        res.send({ post }) 
    })
    .catch((error) => {
        log(error)
        res.status(500).send("Internal Server Error")
    })

})

// This is the route that I can't seem to send requests to
router.get('/allposts', async(req, res) => {
    if (mongoose.connection.readyState != 1) {
        log('Issue with mongoose connection')
        res.status(500).send('Internal server error')
        return;
    }  

    try{
        const allPosts = await Post.find()
        res.send(allPosts)
    } catch(error){
        log(error)
        res.status(500).send("Internal sever error")
    }

})

server.js

const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()

app.use(express.static(path.join(__dirname, '/public')))
app.use(cors())

const log = console.log;
const bodyParser = require('body-parser')
app.use(bodyParser.json());

var user = require("./routes/User.js");
var post = require("./routes/Post.js");

app.use('/users', user);
app.use('/post', post);

const port = process.env.PORT || 3001
app.listen(port, () => {
    log(`Listening on port ${port}...`)
});

When I send a request to http://localhost:3001/post/allposts, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.

CodePudding user response:

Main problem is the order of the routes.

router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.

You need to switch the init order.

First router.get('/allposts') then router.get('/:id').

  • Related