POST请求适用于Postman,但不适用于axios.POST()



我使用节点在React-JSREST-api中创建了一个Note应用程序,同时运行前端和服务器。这是我的RESTApi(我正在使用mongoDB来存储数据(

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.jsx文件中的axios.post

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)
})}

POST请求通过Postman完美地工作,并且我的数据被存储。然而,对于axios.post函数,它确实向我的api发送了一个post请求,但当我console.log(title)console.log(content)时,控制台返回undefined,并且一个空对象被发送回我的mongoDB数据库中的Note集合。我试着在网上找到这个问题,但一直找不到解决方案。任何帮助都将不胜感激。

这是我的全部快递休息API代码

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

`

app.use(express.json())中间件添加到您的代码中,否则express服务器无法从请求中提取JSON数据

您的请求对象似乎不是JSON对象,您需要使用app.use(express.json())

最新更新