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

str*_*ght 11 javascript ajax jquery node.js express

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

在节点中:

 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);
Run Code Online (Sandbox Code Playgroud)

在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');
                },
              });
        })
Run Code Online (Sandbox Code Playgroud)

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

 TypeError: Cannot read property 'id' of undefined
Run Code Online (Sandbox Code Playgroud)

如果我评论这些呼叫,ajax是成功的.我搞不清楚了.我忘记了什么吗?

the*_*ejh 9

req你在那里的对象没有body财产.看看http://expressjs.com/api.html#req.body:

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

因此,您需要将bodyParser中间件添加到您的快速webapp中,如下所示:

var app = express();
app.use(express.bodyParser());
Run Code Online (Sandbox Code Playgroud)


小智 7

通过包含thejh建议的bodyParser中间件确实解决了这个问题.

只需确保访问该答案中提供的URL以访问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);
})
Run Code Online (Sandbox Code Playgroud)

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

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