Nodejs - HTTP - 带可选参数

时间:2018-06-16 18:36:06

标签: node.js http express parameters

我需要在我的节点服务器中进行http调用。可选参数是:

  • 'name ='

这意味着url(相对路径)应如下所示:

/v1/clans?name=**exampleValue**

到目前为止,我的http请求的选项如下:

app.get('/v1/:clans?=:name', (req, res) => {
    console.log(req.path)
    const options = {
        host: 'api.clashofclans.com',
        path: req.path,
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer *token*'
        }
    };
    const x = https.get(options, (request) => {...});

但这并没有成功。有人知道如何在我的路径属性中包含可选参数吗?

1 个答案:

答案 0 :(得分:4)

你不是。这不是你想到的参数。这是一个查询参数,您的路径应如下所示:

'/v1/clans

您在案例req.query.<parameter>

中使用req.query.name检索查询参数

您正在考虑的可选网址参数就像/v1/clans/:name一样,可以使用req.params.name访问。