我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

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

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

根据@kevin-xue所说,需要声明内容类型。在我的实例中,这只发生在IE9中,因为XDomainRequest不设置内容类型,所以bodyparser和expressjs忽略了请求的主体。

我通过在将请求传递给主体解析器之前显式地设置content-type来解决这个问题,如下所示:

app.use(function(req, res, next) {
    // IE9 doesn't set headers for cross-domain ajax requests
    if(typeof(req.headers['content-type']) === 'undefined'){
        req.headers['content-type'] = "application/json; charset=UTF-8";
    }
    next();
})
.use(bodyParser.json());

其他回答

浪费了很多时间:

这取决于客户端请求中的Content-Type 服务器应该有不同的,以下app.use()之一:

app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))

来源:https://www.npmjs.com/package/body-parser bodyparsertextoptions

例子:

对我来说, 在客户端,我有以下标题:

Content-Type: "text/xml"

因此,在服务器端,我使用:

app.use(bodyParser.text({type: 'text/xml'}));

然后,要求。身体工作正常。

中间件总是首先使用。

//MIDDLEWARE
app.use(bodyParser.json());
app.use(cors());    
app.use(cookieParser());

在路线之前。

//MY ROUTES
app.use("/api", authRoutes);

不。你需要在app.use(app.router)之前使用app.use(express.bodyParser())。实际上,app.use(app.router)应该是你调用的最后一个东西。

在表单定义中使用引导类的情况下,首先消除这些类有助于解决问题。我苦苦思索了一段时间,才发现php-email-form类是罪魁祸首。

 <form action="/route/login" method="POST" class="php-email-form row justify-content-center">

这是我今天想到的。以上方法对我都没用。但稍微搜索一下帮助我解决了这个问题。我正在为微信第三方服务器编码。

当node.js应用程序需要读取流POST数据(例如来自REST客户端的请求)时,情况会稍微复杂一些。在这种情况下,请求的属性“readable”将被设置为true,并且POST数据必须以块的形式读取,以便收集所有内容。

http://www.primaryobjects.com/CMS/Article144