async/await 请求
在 Proxyman Scripting 中使用 async/await,从 onRequest 和 onResponse 调用外部 HTTP/HTTPS API:macOS 上使用 $http,Windows/Linux 上使用 axios。
1. 这是什么?
从 macOS 版 Proxyman v3.5.0 和 Windows/Linux 版 Proxyman v2.11.0 或更高版本开始,你可以在脚本中使用 async / await 发起 HTTP/HTTPS 调用,获取外部资源。
信息
- 在 macOS 上:使用 `$http`
- 在 Windows/Linux 上:使用内置的 `axios`
示例:发送 JSON 请求体的 POST 请求(macOS)
async function onResponse(context, url, request, response) {
// Define JSON Body and Header
// Make sure "Content-Type" is "application/json"
var param = {
body: {
"user": {
"name": "Proxyman"
}
},
headers: {
"Content-Type": "application/json"
}
}
// POST request with await
var output = await $http.post("https://httpbin.org/post", param);
// Get Status Code
console.log(output.statusCode);
// Get body
console.log(output.body)
// Get header
console.log(output.headers)
// Done
return response;
}
2. 如何在 macOS 上使用?
请求方法
var output = await $http.get("https://httpbin.org/anything");
var output = await $http.post("https://httpbin.org/anything");
var output = await $http.put("https://httpbin.org/anything");
var output = await $http.patch("https://httpbin.org/anything");
var output = await $http.delete("https://httpbin.org/anything");
输出格式
var output = await $http.get("https://httpbin.org/anything");
console.log(output)
// print
{
"statusCode": <Int>,
"headers": <Object>,
"body": <Object>
}
示例代码
- 带 Query 参数的 GET 请求
- 带 JSON 请求体的 POST 请求
- 带 application/x-www-form-urlencoded 请求体的 POST 请求
- PUT / PATCH / DELETE 请求
信息
更多示例代码请参阅 async/await HTTP 请求代码片段。
3. 如何在 Windows/Linux 上使用?
Windows/Linux 版 Proxyman 内置了 axios 库,因此你可以使用 axios 语法发起 HTTP(S) 请求。
例如:
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
4. 注意事项
- 请确保将
onRequest()和onResponse()定义为 async 函数:
async function onRequest(context, url, request) {
var output = await $http.get("https://httpbin.org/get");
return request;
}
async function onResponse(context, url, request, response) {
var output = await $http.get("https://httpbin.org/get");
return response;
}
- 请求超时时间为 10 秒。
- 内联的 HTTP 请求不会经过 Proxyman 代理,因此不会受到其他调试工具的影响。
- 你可以在
onRequest()和onResponse()中都使用await $http.get() - 请确保请求体类型与 Content-Type 请求头一致。
application/json 格式的 JSON 请求体
var param = {
body: {
"name": "Proxyman",
},
headers: {
"Content-Type": "application/json"
}
}
application/x-www-form-urlencoded 格式的表单请求体
var param = {
body: {
"key1": "value1",
"key2": "value2"
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}