在Node.JS中读取AJAX post变量(使用Express)

时间:2013-02-23 15:37:51

标签: javascript jquery ajax node.js express

我正在尝试获取我在节点应用程序中发送ajax帖子的值。以this post为指导,到目前为止我已经知道了这一点:

在节点中:

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

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

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

 TypeError: Cannot read property 'id' of undefined

如果我评论这些电话,那么ajax就会成功。我搞不清楚了。我忘记了什么吗?

2 个答案:

答案 0 :(得分:9)

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

  

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

因此,您需要将bodyParser中间件添加到您的快速Web应用程序中,如下所示:

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

答案 1 :(得分:7)

通过包含thejh。

建议的bodyParser中间件确实解决了这个问题

请务必访问该答案中提供的网址,以访问Express更新的规范:http://expressjs.com/api.html#req.body

文档提供了此示例(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);
})

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

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