簡體   English   中英

當通過fetch api向控制器發送post數據時,req.body總是{}

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

我正在嘗試處理控制器中的所有發布請求,以及來自另一個控制器的所有導航。 從表單所在的index.ejs文件中,我有一個文本輸入和一個提交按鈕,我正在向同一個文件('/ index')發送一個獲取帖子請求;

我的觀點看起來像這樣:

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

在提交按鈕單擊,我正在觸發一個獲取請求將數據發布到同一個文件,JS看起來像這樣:

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

我有一個控制器定義來處理發布請求:

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

但是,req.body總是= {}; 我已經搜索了解決方案,並嘗試了大部分解決方案,但我仍然得到{};

我是否要通過app.js文件運行每個請求?

您嘗試發送的JSON格式不正確; 你需要在鍵名周圍添加引號:

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

對不起,這是錯的。 我想你只需要使用JSON.stringify

body: JSON.stringify(msg_data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM