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

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

以防有人遇到和我一样的问题;我使用一个url前缀像

http://example.com/api/

哪一个是用路由器设置的

app.use('/api', router); 

然后我有了以下内容

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

修复我的问题是将bodyparser配置放在app.use('/api', router)之上;

最后

// setup bodyparser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

//this is a fix for the prefix of example.com/api/ so we dont need to code the prefix in every route
    app.use('/api', router); 

其他回答

首先,确保在路由之前应用这个中间件(express.urlencoded)。

let app = express();

//response as Json
app.use(express.json()); 

//Parse x-www-form-urlencoded request into req.body
app.use(express.urlencoded({ extended: true }));     

app.post('/test',(req,res)=>{
    res.json(req.body);
});

代码express.urlencoded({extended:true})只响应x-www-form-urlencoded post请求,所以在ajax/XMLHttpRequest/fetch中,确保您正在发送请求。setRequestHeader(“内容类型”、“应用程序/ x-www-form-urlencoded”);头。

就是这样!

添加表达。Urlencoded ({extended: true})到路由可以解决这个问题。

router.post('/save',express.urlencoded({ extended: true }),  "your route");

看来express不再附带body解析器了。我们可能要单独安装。

var express    = require('express')
var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!

更多信息和示例请参阅git页面https://github.com/expressjs/body-parser。

此问题可能是因为您没有使用body-parser(链接)

var express = require('express');
var bodyParser  = require('body-parser');

var app = express();
app.use(bodyParser.json());

中间件总是首先使用。

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

在路线之前。

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