Express.js req.body未定义

我将其作为Express服务器的配置

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 is undefined这是使用的路线示例req.body

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

我读到这个问题是由于缺少引起的,app.use(express.bodyParser());但是如您所见,我在路由之前将其称为。

有什么线索吗?

路易达蒙2020/03/20 10:32:39

If you are using some external tool to make the request, make sure to add the header:

Content-Type: application/json

神奇启人2020/03/20 10:32:39

This is also one possibility: Make Sure that you should write this code before the route in your app.js(or index.js) file.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
斯丁Gil2020/03/20 10:32:39

I solved it with:

app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});
宝儿凯2020/03/20 10:32:38

Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);

JimJim2020/03/20 10:32:38

To work, you need to app.use(app.router) after app.use(express.bodyParser()), like that:

app.use(express.bodyParser())
   .use(express.methodOverride())
   .use(app.router);
SamDavaidGreen2020/03/20 10:32:38

You can try adding this line of code at the top, (after your require statements):

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

As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

Davaid西门2020/03/20 10:32:38

加入您的 app.js

在路由器呼叫之前

const app = express();
app.use(express.json());
老丝猿路易2020/03/20 10:32:38

Express 4,具有内置的正文解析器。无需安装单独的正文解析器。所以下面将工作:

export const app = express();
app.use(express.json());
ProEva2020/03/20 10:32:38

请求标头中的Content-Type确实很重要,尤其是当您从curl或任何其他工具发布数据时。

确保您使用诸如application / x-www-form-urlencoded,application / json之类的东西,这取决于您的帖子数据。将此字段保留为空会混淆Express。

泡芙番长2020/03/20 10:32:38

否。您需要使用app.use(express.bodyParser())之前app.use(app.router)实际上,app.use(app.router)应该是您最后要打的电话。