gpt4 book ai didi

node.js - 无法使用 Node.js 和 Express 框架读取帖子参数

转载 作者:搜寻专家 更新时间:2023-11-01 00:15:19 25 4
gpt4 key购买 nike

我有一个带有 express Framework 的 node.js 服务器。

var express = require('express');
var http = require('http');
var api_helper = require('./helpers/api_helper');
var app = express();

app.use(app.router);
app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);

app.post('/api/nodev1/users/login', function(req, res){
var email = req.param('email', null);
var password = req.param('password', null);
console.log(email);console.log(password);
});

http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

当我尝试向/api/nodev1/users/login 发送请求时,我无法读取参数。我正在尝试使用 curl,如下所示:

curl -d "email=user@example2.com" -d "password=mypassword" http://localhost:8081/api/nodev1/users/login

电子邮件和密码未定义。

最佳答案

您必须将 app.use(app.router) 移动到 app.use(express.bodyParser()) 下方。 app.router 只是一个钩子(Hook),在哪个阶段处理你的路由。如果它出现在 bodyParser 之前,则不会解析正文。

您的代码可能如下所示(以防我无法解释清楚):

var app = express();

app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);

app.use(app.router);

// I added following line so you can better see what happens
app.use(express.logger('dev'));

app.post('/api/nodev1/users/login', function(req, res){ ... }

题外话:express.bodyParser() 只应在您有文件上传时使用。然后你必须注意删除临时文件。如果你没有文件上传,你最好只用

app.use(express.json());
app.use(express.urlencoded());

我只是想添加这个以防你不知道。我遇到了问题,因为我不知道...

为 Express 4 编辑

感谢@jonathan-ong,自 Express 4 以来没有 app.use(app.router):

All routing methods will be added in the order in which they appear. You should not do app.use(app.router). This eliminates the most common issue with Express.

In other words, mixing app.use() and app[VERB]() will work exactly in the order in which they are called.

Read more: New features in 4.x .

关于node.js - 无法使用 Node.js 和 Express 框架读取帖子参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com