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

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

有线索吗?


当前回答

大部分时间需要。由于缺少JSON解析器,body未定义

const express = require('express');
app.use(express.json());

可能缺少体解析器

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

有时由于cros原点没有定义,所以加起来

const cors = require('cors');
app.use(cors())

其他回答

另一种获取空请求的方法。正文,当您忘记输入元素的name属性时…

<input type="text" /> /* give back empty request.body -> {}*/
<input type="text" name="username" /> /* give back request.body -> {"username": "your-input"} */

最新版本的Express (4.x)将中间件从核心框架中分离出来。如果需要正文解析器,则需要单独安装它

npm install body-parser --save

然后在代码中这样做

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())

当我遇到同样的问题时,尽管我知道BodyParser已不再使用 我已经使用了app.use(express.json()) 问题是{对我来说}: 我在放置

app.use (express.json ())

App.use ('api/v1/example', example) =>{涉及路由}

一旦我重新排列这两行;

1 - app.use(express.json())

2 -应用程序(“火/v1/example”,example)

效果很好

中间件总是首先使用。

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

在路线之前。

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

express.bodyParser()需要被告知它正在解析的内容类型。因此,您需要确保在执行POST请求时,包含了“Content-Type”标头。否则,bodyParser可能不知道如何处理POST请求的主体。

如果你使用curl来执行一个POST请求,其中包含一些JSON对象,它看起来会像这样:

curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute

如果使用其他方法,请确保使用合适的约定设置报头字段。