Nodejs-Req.body未定义在post 4.x [英] Nodejs- Req.body undefined in post with express 4.x

查看:200
本文介绍了Nodejs-Req.body未定义在post 4.x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用中间件 body-parser 来编码表单值以获取req.body对象。
但是当我调试我的代码,发现req.body是未定义的。这是我的代码

I am using a middleware body-parser to encoded the form values to get in req.body object. But as I debug my code, found out req.body is undefined. Here is my code

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

收听发布请求

app.post('/newCategory', function (req,res) {

            //express attached the form encoded values into body
            var categoryName = req.body.categoryName;
        });

Html表单

<form action="/newCategory" role="form" method="post" class="form-inline">
    <input type="text" name="categoryName" placeholder="Category name" class="form-control" />
    <input type="submit" value="New Category" class="btn btn-primary" />
</form>


推荐答案

刚刚遇到同样的问题。看起来我解决了我的问题,移动我的代码映射路由之后的urlencoded行。我现在看到req.body的帖子。

Just ran into the same issue. It looks like I resolved my problem by moving my code to map routes after the urlencoded line. I am now seeing req.body in the post.

app.use(bodyParser.urlencoded({ extended: true }));


// Map routes
var controllers = require("./controllers");
controllers.init(app);

这篇关于Nodejs-Req.body未定义在post 4.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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