可以在项目根目录创建 http-client.env.json
文件,定义不同环境下的变量:
{
"development": {
"host": "localhost:8080",
"token": "dev-token"
},
"production": {
"host": "api.example.com",
"token": "prod-token"
}
}
然后在 HTTP 请求文件中引用这些变量:
GET https://{{host}}/api/users
Authorization: Bearer {{token}}
对于敏感信息,可以创建 http-client.private.env.json
文件(此文件通常应加入 .gitignore):
{
"development": {
"apiKey": "dev-secret-key"
},
"production": {
"apiKey": "prod-secret-key"
}
}
可以创建一个包含公共请求头的文件(例如 headers.http
):
# common_headers.http
### 这里定义公共请求头
@contentType = application/json
@authToken = Bearer your-token-here
然后在其他请求文件中引用这些变量:
< ./common_headers.http
GET <https://api.example.com/users>
Content-Type: {{contentType}}
Authorization: {{authToken}}
创建一个 .http
文件用于存储可重用的请求配置:
# lib.http
### 定义公共变量和请求头
@baseUrl = <https://api.example.com>
@contentType = application/json
@token = your-token
### 创建可重用的请求函数
# @name login
POST {{baseUrl}}/auth/login
Content-Type: {{contentType}}
{
"username": "user",
"password": "pass"
}
# 保存返回的token
@authToken = {{login.response.body.token}}
在单个 .http
文件开头定义可用于该文件所有请求的变量:
@host = api.example.com
@port = 8080
@contentType = application/json
@authToken = Bearer token123
### 第一个请求
GET https://{{host}}:{{port}}/api/users
Content-Type: {{contentType}}
Authorization: {{authToken}}
### 第二个请求
POST https://{{host}}:{{port}}/api/users
Content-Type: {{contentType}}
Authorization: {{authToken}}
{
"name": "John Doe"
}