Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does req.body keep returning an empty object?

req.body keeps returning an empty object no matter what I do,

I've tried

var jsonParser = bodyParser.json();

and then adding jsonParser to function -> app.post('/api/get-last-project',jsonParser,(req, res) => { and

app.use(bodyParser.json());

and

app.use(bodyParser.urlencoded({ extended: false }));

here is where i recieve it,

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

here is where I send the request

fetch(url,{
            method: 'POST',
            data: {
                owner: "Charlie",
                projectName: "Charlie's project"
            }
            })

I want to log the req.body, so I know that I can recieve the value and pass it as an argument to my function createProject.create(). I'm sending the request from a react client.

like image 576
LittleMygler Avatar asked May 19 '26 13:05

LittleMygler


1 Answers

JSON needs to be passed as body

Something like

body: JSON.stringify(data), // body data type must match "Content-Type" header

Refer to 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));
like image 129
ch4nd4n Avatar answered May 22 '26 02:05

ch4nd4n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!