'Express routes working with url params but not with specific sub routes

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:


router.post('/', (req, res) => {
    // Endpoint 1 code here

})

router.get('/:id', (req, res) => {
    // Endpoint 2 code

})

// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => { 

    try{
        const ap = await P.find()
        res.send(ap)
    } catch(error){
        log(error)
        res.status(500).send("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)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());

var p = require("./routes/P.js");

app.use('/post', p);

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

When I send a request to http://localhost:3001/post/ap, 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.



Solution 1:[1]

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').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hurricane