HTTP调用节点
概述
HTTP调用节点允许您使用指定的方法、头部和主体向特定URL发起HTTP调用。当您需要与外部API或服务交互时,该节点特别有用。
HTTP调用节点使用Fetch API发起HTTP请求。它支持所有HTTP方法(GET、POST、PUT、DELETE等),并允许您指定自定义标头和请求体。
当使用默认的browser executor时,在向外部API发起HTTP请求时需要注意CORS问题。如果您尝试调用的API不支持对http://tauri.local
的CORS(大多数都不支持),您将会遇到CORS问题。这可能会在输出面板中表现为fetch failed
错误。
可以通过使用Rivet中的Node executor来绕过此问题,它不会执行CORS检查。
- 输入
- 输出
- 编辑器设置
输入项
HTTP调用节点仅在Editor Settings设置为使用输入切换时才有输入。更多信息请参阅该部分。
输出
标题 | 数据类型 | 描述 | 备注 |
---|---|---|---|
Body | string | The body of the HTTP response. | If the response body is not a string, this output will not be ran. |
JSON | object | If the response body is a JSON object, this output will contain the parsed JSON object. | If the response body is not a JSON object, this output will not be ran. |
Status Code | number | The status code of the HTTP response. | |
Headers | object | The headers of the HTTP response. |
编辑器设置
设置 | 描述 | 默认值 | 使用输入切换 | 输入数据类型 |
---|---|---|---|---|
Method | The HTTP method to use for the request (GET, POST, PUT, DELETE, etc.). | GET | Yes | string |
URL | The URL to make the HTTP request to. | (empty) | Yes | string |
Headers | An object representing the headers to include in the HTTP request. | (empty) | Yes | object |
Body | The body of the HTTP request. This is typically used for POST or PUT requests. The value passed in here is not JSON stringified, so if you need a JSON body, use the To JSON node. | (empty) | Yes | string |
非200状态码错误 | 如果启用,当HTTP响应状态码不是200时,节点将报错。 | True | No | N/A |
示例1:向API发起GET请求
- 创建一个HTTP调用节点,将
Method
设置为GET
,并将URL
设置为https://jsonplaceholder.typicode.com/todos/1
。 - 运行图表。您应该在输出面板中看到所有的响应数据,例如头部信息、响应码和响应体。
示例2:向API发起POST请求
- 创建一个HTTP调用节点,将
Method
设置为POST
,将URL
设置为https://jsonplaceholder.typicode.com/posts
。在"Body"设置中启用"Use Input"切换开关,以启用Body的输入端口。 - 创建一个对象节点并将对象设置为:
{
"title": "foo",
"body": "bar",
"userId": 1
}
- 创建一个To JSON Node并将Object Node连接到To JSON Node的
Data
输入。将To JSON Node连接到HTTP Call Node的Body
输入。 - 创建一个Extract Object Path节点,并将HTTP调用节点的
JSON
输出连接到Extract Object Path节点的Object
输入。将Path
设置为$.id
。 - 运行图表。您应该在提取对象路径节点的输出面板中看到创建的帖子ID。
错误处理
如果HTTP请求因任何原因失败,例如网络错误或服务器返回错误状态码,HTTP调用节点将报错。如果启用了Error on non-200 status code
设置,当HTTP响应的状态码不是200时,该节点也会报错。
常见问题
问:我能否使用HTTP调用节点向任何API发起请求?
A: 是的,您可以使用HTTP调用节点向任何支持HTTP方法GET、POST、PUT或DELETE的API发起请求。
问:我可以使用HTTP调用节点在请求体中发送JSON吗?
A: 是的,你可以使用Text Node来创建JSON字符串,并将其连接到HTTP Call Node的Body
输入。
问:我可以使用HTTP调用节点来处理API认证吗?
A: 是的,您可以在HTTP调用节点的Headers
输入中包含认证头信息。但出于安全考虑,不应在图中硬编码敏感信息如API密钥。建议使用Context Node从宿主应用安全地传入敏感信息。