Express.js req.body未定义

node.js Node.js

番长逆天

2020-03-20

我将其作为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());但是如您所见,我在路由之前将其称为。

有什么线索吗?

第2445篇《Express.js req.body未定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
路易达蒙 2020.03.20

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

Content-Type: application/json

神奇启人 2020.03.20

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());
斯丁Gil 2020.03.20

I solved it with:

app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});
宝儿凯 2020.03.20

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

JimJim 2020.03.20

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);
SamDavaidGreen 2020.03.20

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

加入您的 app.js

在路由器呼叫之前

const app = express();
app.use(express.json());
老丝猿路易 2020.03.20

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

export const app = express();
app.use(express.json());
ProEva 2020.03.20

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

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

泡芙番长 2020.03.20

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android