Home > Net >  POST request works with Postman but not with axios.post()
POST request works with Postman but not with axios.post()

Time:12-19

I created a Note app in React-JS and a REST-api using node and I am running both the front-end and the server concurrently . This is my REST-Api (I am using mongoDB to store the data)

app.post('/api/post',(req,res)=>{
let title = req.body.title
let content = req.body.content
console.log(title)
console.log(content)
const newNote = new Note ({
        title: title,
        content: content
    })
newNote.save()})

This is my axios.post in my App.jsx file

function addItem(item){
axios.post("http://localhost:4000/api/post",{
  title:item.title,
  content:item.content
})
.then(res =>{
  console.log(res)
})
.catch(error=>{
  console.log(error)
})}

The POST request works perfectly via Postman and my data gets stored. However for the axios.post function it does send a post request back to my api, but when I console.log(title) and console.log(content) the console returns undefined and an empty object gets sent back to my Note collection in my mongoDB database.I have tried finding the problem online but have not been able to find the solution. Any help would be much appreciated.

This is my entire express rest API code

const express = require("express");
const app = express();
const mongoose = require("mongoose")
const cors = require("cors")

app.use(express.static('public'))
app.use(express.urlencoded({extended:true})) //this line is to parse any information from forms
app.use(cors())
app.set('view engine', 'ejs')
const PORT = 4000

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost:27017/keeperDB');
}

const notesSchema = new mongoose.Schema(
    {title:String,
    content:String}
)
const Note = mongoose.model("Note",notesSchema)

app.get("/api", function(req, res){
  Note.find(function(err,results){
    if (err){
      console.log(err)
    }else{
        res.json(results)   
    }
  })
});
app.post('/api/post',(req,res)=>{

    let title = req.body.title
    let content = req.body.content
    console.log(title)
    console.log(content)
    const newNote = new Note ({
            title: title,
            content: content
        })
    newNote.save()
})


app.listen(PORT, function(){
  console.log(`Server started on port ${PORT}.`);
});

`

CodePudding user response:

Add app.use(express.json()) middleware to you're code otherwise express server can't extract JSON data from request

CodePudding user response:

It seems Your request object is not a JSON object and you need to use app.use(express.json()).

CodePudding user response:

Did you use body-parser middleware for node API? if not take a look at this link Here and use that middleware

  • Related