async/await リクエスト
Proxyman Scripting で async/await を使い、onRequest と onResponse から外部の HTTP/HTTPS API を呼び出せます。macOS では $http、Windows/Linux では axios を使います。
1. 概要
Proxyman macOS v3.5.0 以降、および Windows/Linux 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>
}
サンプルコード
- クエリ付きの GET リクエスト
- JSON ボディを使う POST リクエスト
- application/x-www-form-urlencoded ボディを使う POST リクエスト
- PUT / PATCH / DELETE リクエスト
備考
その他のサンプルコードは async/await による HTTP リクエストのスニペット をご覧ください。
3. Windows/Linux での使い方
Proxyman for Windows/Linux には組み込みの 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 のプロキシを経由しないため、他のデバッグツールの影響を受けません。
await $http.get()はonRequest()とonResponse()の両方で使用できます。- ボディの型が 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"
}
}