我在React-JS和一個REST-apiusing 節點中創建了一個 Note 應用程式,并且我同時運行前端和服務器。這是我的 REST-Api(我使用 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}.`);
});
`
uj5u.com熱心網友回復:
將app.use(express.json())中間件添加到您的代碼中,否則快遞服務器無法從請求中提取 JSON 資料
uj5u.com熱心網友回復:
看來您的請求物件不是JSON物件,您需要使用app.use(express.json()).
uj5u.com熱心網友回復:
您是否為節點 API 使用了 body-parser 中間件?如果不看看這個鏈接這里并使用該中間件
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386077.html
