为什么req.body总是返回一个空对象?

3

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


为什么在app.post中要使用jsonParser - Rohit Choudhary
我在复制到这里之前尝试过它,进行了编辑。 - LittleMygler
尝试在提交数据时使用应用程序类型:application/json。 - Rohit Choudhary
我应该把它放在哪里? - LittleMygler
在头部键中。例如 header {'Accept': 'application/json'}。 - Rohit Choudhary
1个回答

4

需要将JSON作为 body 传递。

类似于:

body: JSON.stringify(data), // body数据类型必须匹配"Content-Type"头部信息

请参考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));

当我在API中收到它时,我应该如何解析它? - LittleMygler
我假设你正在处理JSON。如果它是有效的JSON字符串,那么JSON.parse应该可以工作。 - ch4nd4n
使用body parser吗? - LittleMygler
2
我认为 bodyparser.json 会自动解析。请求体应该只包含一个对象,其中包括您的JSON解码为对象字面量。 - Keith
1
我会做的第一件事是仔细检查您的fetch发送了什么,这在Chrome中很容易完成。在网络检查中,只需仔细检查您发送的内容是否符合预期。 - Keith
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接