![](/img/trans.png)
[英]Why am I getting 'Each child in a list should have a unique "key" prop error' When I have a key assigned?
[英]Why am I getting the error when I have the key and value?
即使在我輸入帶有firstName鍵和填寫值的請求時,仍然收到錯誤“在請求字段中缺少firstName”。 有人有什么想法嗎? 我真的很需要幫助,因為我是新手。 作者是貓鼬的合集,我正在嘗試通過“ if”語句,並返回作者列表。
app.post('/authors', function (req, res) {
const requiredFields = ['firstName', 'lastName', 'userName'];
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`;
console.error(message);
return res.status(400).send(message);
}
});
Author
.findOne({
userName: req.body.userName
})
.then(author => {
if (author) {
const message = `Username already taken`;
console.error(message);
return res.status(400).send(message);
} else {
Author
.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
userName: req.body.userName
})
.then(author => res.status(201).json({
_id: author.id,
name: `${author.firstName} ${author.lastName}`,
userName: author.userName
}))
.catch(err => {
console.error(err);
res.status(500).json({
error: 'Something went wrong'
});
});
}
})
.catch(err => {
console.error(err);
res.status(500).json({
error: 'Something went really really wrong'
});
});
});
解決方案可以是以下任何一種
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/authors', function (req, res) {
const requiredFields = ['firstName', 'lastName', 'userName'];
console.log(req.body);
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`;
console.error(message);
return res.status(400).send(message);
}
});
//Your Other code
});
內容類型:application / json
所有條件都滿足了,我使上面的代碼可以正常工作。
如果您使用Express 4.16.0或更高版本,則可以使用以下命令: app.use(express.json());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.