• V
 

处理传递到HTTP端点的查询参数

问题

您想要访问传递到HTTP端点的查询参数,例如:

http://example.com/hello-query?name=Nick

解决方案

使用来自HTTP In节点发送的消息的 msg.req.query 属性来访问参数。

示例

[{"id":"b34dd1af.4cb23","type":"template","z":"3045204d.cfbae","name":"page","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<html>\n    <head></head>\n    <body>\n        <h1>Hello {{req.query.name}}!</h1>\n    </body>\n</html>","x":290,"y":180,"wires":[["b828f6a6.47d708"]]},{"id":"1052941d.efad6c","type":"http in","z":"3045204d.cfbae","name":"","url":"/hello-query","method":"get","swaggerDoc":"","x":120,"y":180,"wires":[["b34dd1af.4cb23"]]},{"id":"b828f6a6.47d708","type":"http response","z":"3045204d.cfbae","name":"","x":430,"y":180,"wires":[]}]
[~]$ curl http://localhost:1880/hello-query?name=Nick
<html>
    <head></head>
    <body>
        <h1>Hello Nick!</h1>
    </body>
</html>

讨论

msg.req.query 属性是一个包含每个查询参数的键/值对的对象。

在上面的示例中,请求 /hello-query?name=Nick&colour=blue 结果是属性包含:

{
    "name": "Nick",
    "colour": "blue"
}

如果有多个同名的查询参数,它们将作为数组提供。例如,/hello-query?colour=blue&colour=red

{
    "colour": ["blue","red"]
}