24

我正在使用 Node.js,我想查看已发布到我的脚本的所有参数。为了发挥我的作用,routes/index.js我正在做:

app.post('/v1/order', order.create);

然后在我的功能中,我有:

exports.create = function(req, res, next) {
 console.log( req.params );

但它返回一个空数组。但是当我这样做时:

exports.create = function(req, res, next) {
 console.log( req.param('account_id') );

我得到数据。所以我对这里发生的事情有点困惑。

4

4 回答 4

46

req.params
只能在这种模式下获取请求 url 的参数:/user/:name

req.query
获取查询参数(名称)/user?name=123或正文参数。

于 2016-05-30T08:31:48.237 回答
38

req.params 仅包含路由参数,不包含查询字符串参数(来自 GET),也不包含正文参数(来自 POST)。然而, param() 函数会检查所有三个,请参阅:

http://expressjs.com/4x/api.html#req.params

于 2012-05-09T20:40:14.500 回答
14

我有一个类似的问题,并认为我会为出于同样原因来到这里的人发布解决方案。我的 req.params 以空对象的形式出现,因为我在父路由中声明了 URL 变量。解决方案是将此选项添加到路由器:

const router = express.Router({ mergeParams: true });
于 2020-06-05T02:02:10.260 回答
0

使用邮递员,您可以有两种类型的获取请求:

  1. 通过正文使用x-www-form-urlencoded和传递数据。
  2. 使用 url 参数

无论您如何传递数据,您都可以始终使用此代码片段来始终捕获数据。

/*
    * Email can be passed both inside a body of a json, or as 
    a parameter inside the url.

    * { email: 'test@gmail.com' } -> test@gmail.com
    * http://localhost/buyer/get/?email=test@gmail.com -> test@gmail.com
        */
    let { email }: { email?: string } = req.query;
    if (!email) email = req.body.email;
        
    console.log(email);
于 2021-08-16T16:45:06.387 回答