簡體   English   中英

處理Ajax發布請求時,節點js- req.body為空或未定義

[英]Node js- req.body empty or undefined when handling ajax post request

許多用戶提出的這個問題,我看到了所有解決方案,並嘗試實施它們,但對我來說不起作用。 我試圖獲取由ajax發送的node js函數中的數據。 我在app.js中的代碼

var express    = require('express')
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json())

var app = express()

app.post('/'uploadFileProduction',jsonParser,function(req,res){
     console.log("Hooorrey!!!!")
     console.log(req.body)

})

我的Ajax代碼部分是

<script>
    $(function() {
        $('#submit_modal').click(function(e) {
           console.log('desired event fire!!!!!!!')
         e.preventDefault();
        var data = {};
                data.title = "title";
                data.message = "message";

           $.ajax({
               type: "POST",
               url: 'uploadFileProduction',
               data: JSON.stringify(data),

         });
     });
    });
</script>

當我點擊此ajax函數時,我的體內為空。 我嘗試了以下解決方案,但沒有運氣

req.body帖子為空

Express.js POST請求主體為空

Node.js請求主體為空

https://github.com/expressjs/body-parser/issues/101

當我在節點js中打印req時,它正在打印所有數據,但是在正文中它僅是{}。

請幫忙。

我認為問題是因為您將正文作為JSON對象發送,但未指定contentType。 如果不知道正確的內容類型,服務器將不知道如何解析您的身體。 您應該添加它以使工作正常:

$.ajax({
   type: "POST",
   url: 'uploadFileProduction',
   data: JSON.stringify(data),
   contentType: "application/json; charset=utf-8" // <- this is what you should add
});

暫無
暫無

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

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