【问题标题】:Sending json with $.post in express/node在 express/node 中使用 $.post 发送 json
【发布时间】:2015-07-04 12:44:27
【问题描述】:

这是我的 app.js 文件:

var express = require('express');
var app = express();
var path = require('path');
var $ = require('jquery');
var nodemailer = require('nodemailer');


app.use('/static', express.static(path.join(__dirname, 'static')));


app.get('/', function(req, res) {
    res.sendFile('./views/index.html', {"root": __dirname});
});


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

});

还有我来自另一个文件的 post 请求,在提交表单时调用:

$('form').submit(function(e){
    e.preventDefault();
    var content = $('#message').val();
    var email = $('#EmailInput').val();
    var reason = $('#reason').val();

    $.post('/contact', { 'content': content, 'email': email, 'reason': reason }, function(data){
        console.log(data);
    });
})

但是,每当提交表单时,post 请求都是成功的,只是没有传递任何数据。

req 和 req.body 都返回 undefined。我不知道为什么。

【问题讨论】:

  • 你的代码中有console.log(res.body);,它应该是req.body
  • 看起来你正试图在 app.js 中记录响应——你应该记录请求,而不是!
  • 哎呀。即使我改变了它,仍然未定义。还有其他理论吗?
  • "By default, it is undefined,并在您使用 body-parsermulter 等正文解析中间件时填充。"
  • 你会推荐哪一个?

标签: javascript json node.js post express


【解决方案1】:

您需要主体解析器来填充请求对象的主体属性

npm install body-parser

然后包括

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

您的特定用例和调整的文档可以在here找到

编辑:确保在声明路由处理程序之前包含此内容

【讨论】:

  • 非常感谢!非常感谢!
猜你喜欢
  • 2020-03-01
  • 2017-11-17
  • 2022-10-12
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
相关资源
最近更新 更多