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

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

有线索吗?


当前回答

对于那些上面没有一个答案的人来说,我必须在我的前端和express之间启用cors。

你可以这样做:

下载并打开浏览器的CORS扩展,例如: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en 铬,

或通过

添加线条 var歌珥=要求(“歌珥”); app.use(歌珥());

到express app.js页面。(在npm安装cors之后)

其他回答

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

浪费了很多时间:

这取决于客户端请求中的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'}));

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

以防有人遇到和我一样的问题;我使用一个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); 

这也是一种可能性:确保你应该在app.js(或index.js)文件的路由之前编写这段代码。

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

为了工作,你需要在app.use(express.bodyParser())之后加上app.use(app.router),就像这样:

app.use(express.bodyParser())
   .use(express.methodOverride())
   .use(app.router);