简体   繁体   中英

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

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}.`); });

`

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM