Home > OS >  Getting status 404 in POSTMAN even when i try to post
Getting status 404 in POSTMAN even when i try to post

Time:09-18

Im using a hard coded simple array of objects as data here . can someone tell me why i cant post data from postman in to this.Im able to get the data though ,having trouble only with post . my code is below

const express = require('express');
const app = express();

app.use(express.json());

const courses=[
    {id:1,name:'course1'},
    {id:2,name:'course2'},
    {id:3,name:'course3'}


]
app.get('/',(req,res)=>{
    res.send("Hello world")
})



app.get('/api/users',(req,res)=>{
    res.send(courses);
});

app.post('/api/courses',(req,res)=>{
    const course={
        id:courses.length 1,
        name: req.body.name
    };
    courses.push(course);
    res.send(course);
});

app.get('/api/users/:id',(req,res)=>{
    const course = courses.find(c=>c.id===Number(req.params.id));
    if(!course) res.status(404).send("The course with requested ID is not found");
    res.send(course);
});


const port = process.env.PORT || 3000;
app.listen(port,()=>console.log(`listening to port ${port}...`))

CodePudding user response:

I suppose you send your data as x-wwww-form-urlencoded. You will have to parse the body.

Try adding this:

app.use(express.urlencoded())

To avoid the deprication warning you can write this instead (and you can do the same where you parse the json):

app.use(express.urlencoded({ extended: true }))

CodePudding user response:

Try This code and once check That you have to change the GET to POST in the postman

POST http://localhost/api/courses

app.post('/api/courses',(req,res)=>{
    const {course, name} = req.body // __refrence For Destructuring __ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
    let a = parseInt(course) //convert string to int using parseInt
    for (var i = 0; i < courses.length; i  ) {
    courses.push({
       id : id[i] 1,
       name : name[i]
    });
}
    res.send(courses); // return array of object 
}); 

Sorry about that! I have corrected the code Push array into object

  • Related