skip to Main Content

I’m encountering an issue when making a POST request to the /api/notes/addnote endpoint. The server responds with a 404 Not Found error. I have checked the server-side code and verified that the endpoint is correctly defined. Here are the details of my setup:

Server-side:

Framework/Language: Express.js

Code snippet handling the /api/notes/addnote endpoint:

router.post('/addnote', fetchUser, [
    body('tittle', 'Tittle cannot be blank').exists(),
    body('description', 'Description must be atleast 5 characters').isLength({ min: 5 })
], async (req, res) => {
    // If there are any errors in the validation of an express request, return status 400 and the errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    } 

    // Creating a new note in the database and saving it
    const { tittle, description, tag } = req.body;
    const note = await Notes.create({
        tittle,
        description,
        tag,
        user: req.id
    });

    // Sending the note as a response
    res.json(note);
});

module.exports = router;

main.js file code:

const connectToMongo = require('./Db');
const express = require('express');

connectToMongo();

const app = express()
const port = 3000

app.use(express.json());

app.use('/api/notes/addnote', require('./Routes/notes'));

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

Client-side:

Code snippet for making the POST request:

enter image description here

The server is running and accessible at localhost:3000

I have successfully tested other endpoints on the same server, and they are working correctly.

I have confirmed the URL for the POST request: http://localhost:3000/api/notes/addnote.

I have already attempted the following troubleshooting steps:

  • Double-checked the server-side code and endpoint spelling.

  • Tested the POST request using different HTTP clients (e.g., Postman) with the same result.

  • Reviewed the server logs for any error messages related to the /api/notes/addnote endpoint.

Despite these efforts, I’m still receiving a 404 Not Found error. Any guidance or suggestions on how to resolve this issue would be greatly appreciated. Thank you!

2

Answers


  1. The routes aren’t defined right. Change:

    app.use('/api/notes/addnote', require('./Routes/notes'));
    

    To

    app.use('/api/notes', require('./Routes/notes'));
    
    Login or Signup to reply.
  2. The URL while setting the Router to the appliction is the same as you have mentioned.

    app.use('/api/notes', require('./Routes/notes'));
    

    The problem here is:

    app.use('/api/notes/addnote', require('./Routes/notes'));
    router.post('/addnote');
    

    Now the route works for /api/notes/addnote/addnote.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search