简体   繁体   English

在express中合并req.params和req.url

[英]Merging req.params and req.url in express

First of all, I have the following route: 首先,我有以下路线:

route: '/list/:param1'

Im sending the following request to the server: 我将以下请求发送到服务器:

url: '/list/someParam?param2=foo&param3=bar

After that, express is giving to me two important objects that i need, the req.url and the req.params . 之后,express给我提供了我需要的两个重要对象, req.urlreq.params

I want to get an object that merges both url and params. 我想要一个合并了url和params的对象。 Im using the following code: 我正在使用以下代码:

module.exports = function (req, res, next) {
    var url = require('url');
    var queryObject = url.parse(req.url, true).query;

    console.log(queryObject);
    console.log(req.params);
    console.log(req.params.length);
}

So it logs something like: 因此它记录如下:

{ param2: 'foo', param3: 'bar' }
[ param1: 'someParam' ]
0

Now, assuming that I dont know the name of the params, I need to have an object with the information from both req.url and req.params . 现在,假设我不知道参数的名称,我需要一个对象,其中包含来自req.urlreq.params的信息。 Here are my questions: 这是我的问题:

1) How can I do to get something like: 1)我该怎么做才能得到类似的东西:

{ param1: 'someParam', param2: 'foo', param3: 'bar' }

2) Why is req.params logging something like an array? 2)为什么req.params记录类似数组的东西? And if it is an array, why is it returning me 0 as its length? 如果它是一个数组,为什么它返回0作为长度?

Thanks in advance. 提前致谢。

  1. Use req.query instead of parsing the URL again. 使用req.query而不是再次解析URL。
  2. I'm guessing Express has a custom toString implementation for that particular object. 我猜Express对该特定对象具有自定义的toString实现。

You can also look up both in order of importance using req.param(name) 您还可以使用req.param(name)按重要性顺序查找两者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM