无论我做什么,req.body都会不断返回空对象
我尝试过
var jsonParser = bodyParser.json();
,然后将jsonParser添加到函数-> app.post('/ api / get-last-project',jsonParser,(req,res)=> { 和
app.use(bodyParser.json());
和
app.use(bodyParser.urlencoded({ extended: false }));
这是我收到的地方,
app.post('/api/get-last-project',(req, res) => {
var theProject;
var theQuestions;
var theAnswers;
var qp;
projectModel.findOne().sort({date: -1}).exec(function(err, doc) {
if(!err)
{
if(doc)
{
console.log("hitta");
theProject = doc;
theQuestions = doc.questions.map(question => {
questionModel.findById(question._id);
theAnswers.push(question.answerIds.map(answer => {
answerModel.findById(answer._id);
}))
})
qp = questionPackageModel.findOne(projectId = doc._id);
res.send(fetchedMaterial = {theProject, theQuestions, theAnswers, qp});
}
else{
console.log("skapa");
console.log(req.body) //here it logs {} no matter what I do..
createdMaterial = createProject.create(req.body);
res.send(createdMaterial);
}
}
else{
console.log(err);
}
})
})
这是我发送请求的地方
fetch(url,{
method: 'POST',
data: {
owner: "Charlie",
projectName: "Charlie's project"
}
})
我想记录req.body,所以我知道我可以接收该值并将其作为参数传递给我的函数createProject.create()。 我正在从React客户发送请求。
答案 0 :(得分:1)
JSON必须以body
类似
body: JSON.stringify(data), // body data type must match "Content-Type" header
请参阅https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));