jQuery 在 Node.JS 中读取 AJAX 发布变量(使用 Express)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15042245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:16:23  来源:igfitidea点击:

Reading AJAX post variables in Node.JS (with Express)

javascriptjqueryajaxnode.jsexpress

提问by streetlight

I'm trying to get the values I'm sending for an ajax post in my node application. Using this postas a guide, I have this so far:

我正在尝试获取我为节点应用程序中的 ajax 帖子发送的值。使用这篇文章作为指导,到目前为止我有这个:

In Node:

在节点中:

 var express = require('express');
 var app = express();

 var db = require('./db');

 app.get('/sender', function(req, res) {
    res.sendfile('public/send.html');
 });

 app.post('/send_save', function(req, res) {
  console.log(req.body.id)
  console.log(req.body.title);
  console.log(req.body.content);
  res.contentType('json');
  res.send({ some: JSON.stringify({response:'json'}) });
});

app.listen(3000);

On on the AJAX side:

在 AJAX 方面:

$('#submit').click(function() {
            alert('clicked')
            console.log($('#guid').val())
            console.log($('#page_title').val())
            console.log($('#page-content').val())
            $.ajax({
                url: "/send_save",
                type: "POST",
                dataType: "json",
                data: {
                    id: $('#guid').val(),
                    title: $('#page_title').val(),
                    content: $('#page-content').val()
                },
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                  //called when complete
                  console.log('process complete');
                },

                success: function(data) {
                  console.log(data);
                  console.log('process sucess');
               },

                error: function() {
                  console.log('process error');
                },
              });
        })

This issue is that I can't req.body.id (and any other value like title or content), I'm getting this error in node:

这个问题是我不能 req.body.id (以及任何其他值,如标题或内容),我在节点中收到此错误:

 TypeError: Cannot read property 'id' of undefined

If I comment those calls out though, the ajax is successful. I am lost. Am I forgetting something?

但是,如果我注释掉这些调用,则 ajax 是成功的。我搞不清楚了。我是不是忘记了什么?

采纳答案by thejh

The reqobject you have there has no bodyproperty. Have a look at http://expressjs.com/api.html#req.body:

req您在那里拥有的对象没有任何body属性。看看http://expressjs.com/api.html#req.body

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

此属性是一个包含已解析请求正文的对象。此功能由 bodyParser() 中间件提供,但其他正文解析中间件也可能遵循此约定。使用 bodyParser() 时,此属性默认为 {}。

So, you need to add the bodyParser middleware to your express webapp like this:

因此,您需要像这样将 bodyParser 中间件添加到您的 express 网络应用程序中:

var app = express();
app.use(express.bodyParser());

回答by Lex L.

The issue was indeed resolved by including the bodyParser middleware as suggested by thejh.

该问题确实通过包含 thejh 建议的 bodyParser 中间件解决了。

Just make sure to visit the url provided in that answer as to visit Express updated specification: http://expressjs.com/api.html#req.body

只需确保访问该答案中提供的 url 以访问 Express 更新的规范:http: //expressjs.com/api.html#req.body

The documentation provides this example (Express 4.x):

文档提供了这个例子(Express 4.x):

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
  console.log(req.body);
  res.json(req.body);
})

For this to work the body-parser module needs to be installed separately:

为此,需要单独安装 body-parser 模块:

https://www.npmjs.com/package/body-parser

https://www.npmjs.com/package/body-parser