• V
 

处理HTTP端点中的URL参数

问题

您想创建一个单一的HTTP端点,可以处理请求,其中请求路径的部分是根据请求设置的。

例如,一个单一的端点可以处理对以下两个请求的请求:

http://example.com/hello-param/Nick
http://example.com/hello-param/Dave

解决方案

在您的HTTP In节点的URL属性中使用命名路径参数,然后使用消息的msg.req.params属性访问请求中提供的特定值。

流程

[{"id":"ce53954b.31ac68","type":"http response","z":"3045204d.cfbae","name":"","x":490,"y":280,"wires":[]},{"id":"288a7c0.fd77584","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.params.name}}!</h1>\n    </body>\n</html>","x":350,"y":280,"wires":[["ce53954b.31ac68"]]},{"id":"7665c67d.899a38","type":"http in","z":"3045204d.cfbae","name":"","url":"/hello-param/:name","method":"get","swaggerDoc":"","x":150,"y":280,"wires":[["288a7c0.fd77584"]]}]

示例

[~]$ curl http://localhost:1880/hello-param/Nick
<html>
    <head></head>
    <body>
        <h1>Hello Nick!</h1>
    </body>
</html>

讨论

URL属性中的命名路径参数可用于识别在请求之间可以变化的路径部分。

msg.req.params属性是每个路径参数的键/值对对象。

在以上示例中,节点配置了一个URL为/hello-params/:name,因此对/hello-param/Nick的请求导致msg.req.params属性包含:

{
    "name": "Nick"
}