为什么req.body不断返回空对象?

小米格勒

无论我做什么,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客户端发送请求。

ch4nd4n

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章