# async/await 请求

> 在 Proxyman Scripting 中使用 async/await，从 onRequest 和 onResponse 调用外部 HTTP/HTTPS API：macOS 上使用 $http，Windows/Linux 上使用 axios。

## 1. 这是什么？ {#1-whats-it}

从 macOS 版 Proxyman v3.5.0 和 Windows/Linux 版 Proxyman v2.11.0 或更高版本开始，你可以在脚本中使用 `async / await` 发起 HTTP/HTTPS 调用，获取外部资源。

> **备注:**
>
> * 在 macOS 上：使用 \`$http\`
> * 在 Windows/Linux 上：使用内置的 \`axios\`

### 示例：发送 JSON 请求体的 POST 请求（macOS） {#sample-post-request-with-json-body-macos}

```javascript
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 上使用？ {#2-how-to-use-on-macos}

### 请求方法 {#method}

```javascript
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");
```

### 输出格式 {#output-format}

```javascript
var output = await $http.get("https://httpbin.org/anything");
console.log(output)

// print
{
    "statusCode": <Int>,
    "headers": <Object>,
    "body": <Object>
}
```

### 示例代码 {#sample-code}

* [带 Query 参数的 GET 请求](https://proxyman.com/docs/zh-cn/scripting/snippet-code#get-request-with-query)
* [带 JSON 请求体的 POST 请求](https://proxyman.com/docs/zh-cn/scripting/snippet-code#post-request-with-json-body)
* [带 application/x-www-form-urlencoded 请求体的 POST 请求](https://proxyman.com/docs/zh-cn/scripting/snippet-code#post-request-with-applicationx-www-form-urlencoded-body)
* [PUT / PATCH / DELETE 请求](https://proxyman.com/docs/zh-cn/scripting/snippet-code#put--patch--delete-request)

> **备注:** 更多示例代码请参阅 [async/await HTTP 请求代码片段](https://proxyman.com/docs/zh-cn/scripting/snippet-code#make-asyncawait-http-request-macos)。

## 3. 如何在 Windows/Linux 上使用？ {#3-how-to-use-on-windowslinux}

Windows/Linux 版 Proxyman 内置了 [axios](https://github.com/axios/axios) 库，因此你可以使用 axios 语法发起 HTTP(S) 请求。

例如：

```javascript
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
```

## 4. 注意事项 {#4-notes}

* 请确保将 `onRequest()` 和 `onResponse()` 定义为 **async** 函数：

```javascript
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 请求体**

```javascript
var param = {
    body: {
      "name": "Proxyman",
    },
    headers: {
      "Content-Type": "application/json"
    }
  }
```

**application/x-www-form-urlencoded 格式的表单请求体**

```javascript
var param = {
    body: {
      "key1": "value1",
      "key2": "value2"
    },
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  }
```
