【问题标题】:Receiving Jquery POST data in Express在 Express 中接收 Jquery POST 数据
【发布时间】:2017-02-21 10:19:44
【问题描述】:

编辑请参阅下面接受的答案以获取修复。我还必须从我的 POST 请求中删除行 contentType: 'appliction/json',

我正在尝试向 Node.js / Express 发送一个字符串,但 req.body 是未定义的服务器端。

客户端 jQuery:

$.post({
        traditional: true,
        url: '/matches',
        contentType: 'appliction/json',
        data: viewedProfiles,
        dataType: 'json',
        success: function(response){

快递:

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post('/matches', isLoggedIn, function(req, res){
  console.log(req.body) // this is undefined
  var loadedProfiles = []
  loadedProfiles.push(req.body.viewedProfiles)
  console.log('loadedProfiles')
  console.log(loadedProfiles)

我试过了:

  • 未指定“数据类型”
  • 设置data: JSON.stringify(viewProfiles)
  • 在客户端将字符串拆分成数组,然后让 jQuery 对其进行字符串化
  • 寻找 req.params 而不是 req.body(抓着稻草)

我可以在开发工具中看到 XHR 请求,它包含我期望的字符串。

在将数据发送到 Express 时,我错过了什么特别明显的事情?

谢谢。

【问题讨论】:

  • 您的页面中是否运行了connect 中间件?
  • 我没有,但我有 jQuery 数据帖子在应用程序的其他地方成功运行。

标签: javascript jquery node.js express post


【解决方案1】:

您的服务器端代码看起来不错,但您需要使用$.ajax() 而不是$.post() 函数,因为$.post() 函数将数据发送到url(带有url 编码)。所以你的 JQuery 代码是

$.ajax({
        url: '/matches',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({"viewedProfiles": viewedProfiles}),
        success: function(response){

希望对你有帮助

【讨论】:

  • 是的,这对我很有帮助!我还必须删除行 contentType: 'appliction/json', 才能正常工作。
【解决方案2】:

我已经配置了完全相同的设置。下面的代码有效:

var profiles = { 'data' : 'hello' };

$.post({
        traditional: true,
        url: '/matches',
        contentType: 'application/json',
        data: JSON.stringify( profiles ),
        dataType: 'json',
        success: function(response){ console.log( response ); }
} );

我的 nodejs 引擎:

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post( '/matches' , function(req, res){
  console.log(req.body) // this outputs: { data: 'hello' }
} );

顺便说一句,你的 contentType 有一个错字,'applicAtion/json'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2011-02-13
    • 1970-01-01
    • 2020-07-21
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多