Req.body 为空 object 执行放置请求时
Req.body is empty object when performing a put request
我正在执行从前端到后端的 PUT 请求,其中后端函数更新我的 Firestore 数据库。该函数本身工作正常(可以通过邮递员等调用)但不能从前端调用,因为 req.body 将始终为空 object。我当然检查了许多其他类似的案例,添加了一堆 headers 和其他东西但是 none 已经解决了我的问题。这是我的后端代码:
router.put('/:id/results', async (req, res) => {
try {
console.log("Updating results...") //THIS IS LOGGED
console.log(req.body) // THIS LOGS {}
let hamsters = []
console.log(req.params.id) //LOGS ID
let snapShots = await db.collection('hamsters').where("id", "==", parseInt(req.params.id)).get()
snapShots.forEach(doc => {
hamsters.push(doc.data())
})
if (req.body.wins == 1) {
hamsters[0].wins++
res.send(`${hamsters[0].name} now has ${hamsters[0].wins} wins!`)
} else if (req.body.defeats == 1) {
hamsters[0].defeats++
res.send(`${hamsters[0].name} now has ${hamsters[0].defeats} defeats!`)
} else {
throw ("You must either increase wins or defeats by 1") //THIS IS LOGGED
}
hamsters[0].games++
db.collection('hamsters').doc(req.params.id).set(hamsters[0])
}
catch (err) {
console.error(err)
}
})
我的前端函数有两种不同的方法,具体取决于结果参数,它们现在看起来略有不同只是为了说明我如何编写请求似乎并不重要。该函数目前没有 return 任何内容,因为它只需要更新数据库。
export async function putBattleStats(hamsterID, outcome) {
try {
if (outcome === "win") {
const response = await fetch(`/hamsters/${hamsterID}/results`,
{
method: 'PUT', headers: { "Content-Type": "application/json/x-www-form-urlencoded" }, body: {
"hamsterID": JSON.stringify(hamsterID),
"wins": +1
}
})
} else if (outcome === "defeat") {
const response = await fetch(`/hamsters/${hamsterID}/results`,
{
method: 'PUT', body: {
"hamsterID": hamsterID,
"defeats": +1
}
})
}
}
catch (e) {
console.error('Fetch failed because', e)
return null
}
}
就像我说的,我尝试了各种 headers,我安装了 node-fetch,我也把这些行放在我的 server.js 文件中:
const bodyParser = require('body-parser')
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json())
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
我只是希望我遗漏了一些明显的东西。
可能是因为您没有对整个正文进行字符串化。
试试这个:
const response = await fetch(`/hamsters/${hamsterID}/results`,
// change this URL
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
// this can just be 'application/json' in your case
body: JSON.stringify({
hamsterID: hamsterID,
wins: 1
})
})
我正在执行从前端到后端的 PUT 请求,其中后端函数更新我的 Firestore 数据库。该函数本身工作正常(可以通过邮递员等调用)但不能从前端调用,因为 req.body 将始终为空 object。我当然检查了许多其他类似的案例,添加了一堆 headers 和其他东西但是 none 已经解决了我的问题。这是我的后端代码:
router.put('/:id/results', async (req, res) => {
try {
console.log("Updating results...") //THIS IS LOGGED
console.log(req.body) // THIS LOGS {}
let hamsters = []
console.log(req.params.id) //LOGS ID
let snapShots = await db.collection('hamsters').where("id", "==", parseInt(req.params.id)).get()
snapShots.forEach(doc => {
hamsters.push(doc.data())
})
if (req.body.wins == 1) {
hamsters[0].wins++
res.send(`${hamsters[0].name} now has ${hamsters[0].wins} wins!`)
} else if (req.body.defeats == 1) {
hamsters[0].defeats++
res.send(`${hamsters[0].name} now has ${hamsters[0].defeats} defeats!`)
} else {
throw ("You must either increase wins or defeats by 1") //THIS IS LOGGED
}
hamsters[0].games++
db.collection('hamsters').doc(req.params.id).set(hamsters[0])
}
catch (err) {
console.error(err)
}
})
我的前端函数有两种不同的方法,具体取决于结果参数,它们现在看起来略有不同只是为了说明我如何编写请求似乎并不重要。该函数目前没有 return 任何内容,因为它只需要更新数据库。
export async function putBattleStats(hamsterID, outcome) {
try {
if (outcome === "win") {
const response = await fetch(`/hamsters/${hamsterID}/results`,
{
method: 'PUT', headers: { "Content-Type": "application/json/x-www-form-urlencoded" }, body: {
"hamsterID": JSON.stringify(hamsterID),
"wins": +1
}
})
} else if (outcome === "defeat") {
const response = await fetch(`/hamsters/${hamsterID}/results`,
{
method: 'PUT', body: {
"hamsterID": hamsterID,
"defeats": +1
}
})
}
}
catch (e) {
console.error('Fetch failed because', e)
return null
}
}
就像我说的,我尝试了各种 headers,我安装了 node-fetch,我也把这些行放在我的 server.js 文件中:
const bodyParser = require('body-parser')
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json())
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
我只是希望我遗漏了一些明显的东西。
可能是因为您没有对整个正文进行字符串化。
试试这个:
const response = await fetch(`/hamsters/${hamsterID}/results`,
// change this URL
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
// this can just be 'application/json' in your case
body: JSON.stringify({
hamsterID: hamsterID,
wins: 1
})
})