Express继续获取request.body作为未定义的JSON对象 [英] Express keeps getting request.body as undefined JSON object

查看:394
本文介绍了Express继续获取request.body作为未定义的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个如下所示的Ajax请求:

I am making an Ajax request that looks like this:

 $.ajax({
        url: '/gen',
        type: 'POST',
        data: JSON.stringify({'one': 1, 'two':2}),
        success: function(data) {console.log(this)}
    });

我的快递部分如下:

 var express = require('express');
 var app = express();
 var router = express.Router(); 

 app.set('port', (process.env.PORT || 5000));

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

这总是在控制台中输出 undefined

this always outputs undefined in the console.

如何改变这个以使req.body或req的任何部分包含我试图发送到的快递部分的信息。代码。

How can I change this around to make the req.body, or any part of the req, contain the information I am trying to send over to the express portion of the code.

推荐答案

您需要使用正文解析器。

You need to use the body parser.

var bodyParser = require('body-parser')

app.use(bodyParser.json());

参见:

  • https://github.com/expressjs/body-parser

您可能还需要添加:

contentType: 'application/json',

.ajax()期权。

这篇关于Express继续获取request.body作为未定义的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆