Sunday, 7 May 2017

The req.body is always {} when sending post data through fetch api to a controller

I'm trying to handle all post requests in a controller, and all navigation from another controller. From the index.ejs file where the form is located, i've a text input and a submit button, I'm firing a fetch post request to same file ('/index');

my view looks like this :

<form id='message'>
    <input type='text' id='message' placeholder='Type a Message' name="message" />
    <button id='send'>Send</button>
  </form>

on the submit button click, i'm firing a fetch request to post data to the same file, JS looks like this :

btn.onclick = ()=>{
  var msg = document.getElementById('message').value;
  var data = {
    message : msg,
    sender : usr,
    time : new Date()
  }

  send_to_server(data);
  display_and_cache(data);
}

function send_to_server(msg_data){
  console.log(msg_data);
  fetch('/index',{
    method : 'POST',
    body  : msg_data,
    headers : new Headers({
      'Content-type' : 'application/json'
    })
  }).then(()=>{
    console.log('sent the post request');
  })
  .catch((err)=>{
    console.log('can\'t fetch');
  })
}

i've a controller defined to deal with the post request :

module.exports = (app)=>{
  var bodyParser = require('body-parser');
  var urlencoded = bodyParser.urlencoded({extended : false});
  var json = bodyParser.json();
  app.use(bodyParser.json());
  // Control for message sending to the server.
  app.post('/index',(req,res)=>{
    console.log('request recieved');
    var resp = {
      status : 200,
      ok : true,
    }
    console.log(req.body);
    res.send(resp);
  })
}

but, the req.body is always = {}; I've searched for solutions and tried most of them, but still i'm getting {};

Do i've to run every request through my app.js file?



via Anubhav Tiwari

No comments:

Post a Comment