javascript - Node js- req.body 在处理 ajax post 请求时为空或未定义

标签 javascript node.js ajax

许多用户问的这个问题我看到了所有的解决方案并尝试实现它们,但它对我不起作用。 我正在尝试获取由 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 empty on posts

Express.js POST req.body empty

Node.js req.body empty

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

当我在 Node js 中打印请求时,它会打印所有数据,但在正文中它只是 {}。

请帮忙。

最佳答案

我认为问题是因为您将正文作为 JSON 对象发送,但未指定 contentType。服务器不知道如何在不知道正确内容类型的情况下解析您的正文。您应该添加它以使事情正常进行:

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

关于javascript - Node js- req.body 在处理 ajax post 请求时为空或未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51961751/

相关文章:

javascript - 弹出窗口关闭后在原始页面中显示 jQuery ajax 变量

javascript - 方法不是函数

javascript - 将本地 CSV 文件读入二维数组 - Javascript

node.js - 使用 Nodejs Crypto 模块的非对称加密

jquery - 通过 ajax 访问 Wunderlist API http 来列出任务

javascript - ajax 成功或失败之前调用函数

javascript - json 获取对象而不知道它的名称

javascript - 是否可以将 CSS 应用于字符的一半?

javascript - 将空格插入跨度内的文本失败

node.js - app 在环回自定义 js 文件中未定义