Express js req.body返回空 [英] Express js req.body returns empty

查看:119
本文介绍了Express js req.body返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试过其他一些stackoverflow帖子的所有解决方案,但它没有解决我的问题。

I've tried the all solutions from some another stackoverflow posts but it didn't solved my issue.

这是我的应用。 js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');



var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var index = require('./routes/index');
var v1    = require('./routes/route');

app.use('/', index);
//routes for api
app.use('/v1',v1);

这是我的帖子控制器

module.exports = {

    createUser:function (req,res) {
        console.log(req.body);
        res.send('ok'+req.body.test);
    }
}

req.body 也会返回 {}

我正在检查api的邮差插件。

I am checking the api's with postman plugin.

更新

邮递员请求

推荐答案

body-parser

bodyParser对象公开了各种工厂来创建中间件。所有中间件都将使用已解析的正文填充 req.body 属性,如果没有,则填充空对象 {} 要解析的正文(或返回错误)。

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body, or an empty object {} if there was no body to parse (or an error was returned).

app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies




包含已解析数据的新体对象是在中间件之后填充在请求对象上, req.body 将包含已解析的数据,此对象将包含键值对,其中值可以是字符串或数组

A new body object containing the parsed data is populated on the request object after the middleware, req.body will contain the parsed data, this object will contain key-value pairs, where the value can be a string or array

Content-Type是 application / x-www-form-urlencoded

The Content-Type is application/x-www-form-urlencoded

app.use(bodyParser.json()); // for json encoded bodies




包含解析数据的新主体对象在中间件之后填充请求对象(即 req.body )。

Content-Type是 application / json

The Content-Type is application/json

<当您发布数据 {test:hello} 时,会使用code> application / json www-form-url-encoded 用于在使用 app.use(bodyParser)时从url获取对象中的键值。 urlencoded({extended:true})); 。它们都不同,并有自己的用例

application/json is used when you are posting the data {"test":"hello"} like this. www-form-url-encoded is used to get the data as key-value in object from the url when used the app.use(bodyParser.urlencoded({ extended: true }));. They both are different and have their own use cases

这篇关于Express js req.body返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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