实际上,使用 Axios 发送 HTTP 头部有几种方法。例如,您可以按照此处的描述使用配置对象,或者使用实例方法,这些方法会自动将您传递的配置与实例配置合并。您还可以使用 `axios.defaults.headers.common` 对象为所有 Axios 请求设置默认头部。
此外,请注意 Axios 是一个基于 Promise 的 HTTP 客户端。这意味着我们需要在异步函数中等待请求完成,或者手动解析响应。
考虑到这两个方面,让我们开始实际编写代码。我们将使用 ‘index.js’ 文件进行操作。为方便起见,让我们先回顾一下需要做的事情:
- 在文件中导入 `axios`
- 定义一个用于存储请求头信息的配置对象
- 将配置传递给 `axios` 以发起请求
- 在终端中输出响应
#1:使用配置对象发送 GET 请求
import axios from "axios"
const config = {
method: 'GET',
url: 'https://httpbin.org/headers',
headers: {
'HTTP-Axios-Headers': 'This is my custom header.'
}
}
axios(config)
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
})
使用 Axios 发送 HTTP 头部再简单不过了。要执行此脚本,只需在终端中运行以下命令:
~ » node index.js
{
status: 200,
statusText: 'OK',
headers: ...,
config: ...,
request: ...,
data: {
headers: {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, compress, deflate, br',
'Host': 'httpbin.org',
'Http-Axios-Headers': 'This is my custom header.',
'User-Agent': 'axios/1.2.2',
'X-Amzn-Trace-Id': 'Root=1-63b54d94-7656f02113483dfa036c476c'
}
}
}
整个响应数据量较大,且遵循以下结构。不过,我们主要关注的是 `data` 字段,它包含从服务器接收到的实际响应。现在请查看上方的响应。请记住,我们向服务器发送了自定义标头 `Http-Axios-Headers`,如您所见,服务器确实接收到了该标头。
#2:使用方法别名发送 POST 请求
import axios from "axios"
const data = {
'foo':'bar'
}
const config = {
headers: {
'HTTP-Axios-Headers': 'This is my custom header.'
}
}
axios.post('http://httpbin.org/post', data, config)
.then(response => console.log(response.data))
.catch(err => console.log(err))
请注意,为了发送 POST 请求,我在脚本中添加了一个新的 `data` 对象,并修改了 URL。现在,如果你运行该脚本,你会发现这是从服务器接收到的数据:
{
args: {},
data: '{"foo":"bar"}',
files: {},
form: {},
headers: {
Accept: 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, compress, deflate, br',
'Content-Length': '13',
'Content-Type': 'application/json',
Host: 'httpbin.org',
'Http-Axios-Headers': 'This is my custom header.',
'User-Agent': 'axios/1.2.2',
'X-Amzn-Trace-Id': 'Root=1-63b5508a-3a86493f087662d3169e80ee'
},
json: { foo: 'bar' },
origin: '49.12.221.20',
url: 'http://httpbin.org/post'
}