• V
 

使用模板设置请求的 URL

问题

您想动态设置 HTTP 请求的 URL,其中只有 URL 的某些部分在请求之间发生变化。

解决方案

配置 HTTP Request 节点以使用 mustache URL 模板动态生成 URL。

示例

[{"id":"41747a17.54ffd4","type":"http request","z":"c9a81b70.8abed8","name":"","method":"GET","ret":"txt","url":"https://jsonplaceholder.typicode.com/posts/{{post}}","tls":"","x":550,"y":480,"wires":[["d682318c.36823"]]},{"id":"d682318c.36823","type":"debug","z":"c9a81b70.8abed8","name":"","active":true,"console":"false","complete":"payload","x":710,"y":480,"wires":[]},{"id":"90bfea22.dd2b98","type":"inject","z":"c9a81b70.8abed8","name":"帖子 ID","topic":"","payload":"2","payloadType":"str","repeat":"","crontab":"","once":false,"x":250,"y":480,"wires":[["e67a0cc.596d4f"]]},{"id":"e67a0cc.596d4f","type":"change","z":"c9a81b70.8abed8","name":"","rules":[{"t":"set","p":"post","pt":"msg","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":390,"y":480,"wires":[["41747a17.54ffd4"]]}]

在此流程中,Inject 节点发送我们希望从 API 请求的帖子的 ID。Change 节点将其修改为 msg.postHTTP Request 节点通过替换 URL 属性中的 msg.post 来生成 URL,如下所示:

https://jsonplaceholder.typicode.com/posts/{{post}}

来自此 API 的 JSON 输出将在调试面板中显示如下:

{
  "userId": 1,
  "id": 2,
  "title": "qui est esse",
  "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}

讨论

默认情况下,mustache 会转义其替换值中的任何 HTML 实体。要确保在 URL 中不使用 HTML 转义,请使用 {{{triple}}} 大括号。