简体   繁体   中英

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?

The JSON you're trying to send is malformed; you need to add quotes around the key names:

 var data = { "message": msg, "sender": usr, "time": new Date() } 

Yeah sorry that's wrong. I think you just need to use JSON.stringify :

body: JSON.stringify(msg_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM