怎么使用axios发送请求
To set headers in an Axios POST request, pass a third object to the axios.post()
call.
要在Axios POST请求中设置标头,请将第三个对象传递给axios.post()
调用。
You might already be using the second parameter to send data, and if you pass 2 objects after the URL string, the first is the data and the second is the configuration object, where you add a headers
property containing another object:
您可能已经在使用第二个参数发送数据,并且如果在URL字符串后传递2个对象,则第一个是数据,第二个是配置对象,在其中添加包含另一个对象的headers
属性:
axios.post(url, {
data: {
...
}
})
axios.post(url, {
//...data
}, {
headers: {
...
}
})
To set the authorization header, call it like this:
要设置授权标头,请按以下方式调用它:
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
(the authorization token might differ, check with the app you’re using)
(授权令牌可能会有所不同,请与您使用的应用程序核对)
To set headers in an Axios GET request, pass a second object to the axios.get()
call, for example this is a GitHub GET request to /user
:
要在Axios GET请求中设置标头,请将第二个对象传递给axios.get()
调用,例如,这是对/user
的GitHub GET请求:
axios.get('https://api.github.com/user', {
headers: {
'Authorization': `token ${access_token}`
}
})
.then((res) => {
console.log(res.data)
})
.catch((error) => {
console.error(error)
})
I was doing some work with the WordPress API, and I had to authenticate to perform a POST request to a website.
我正在使用WordPress API进行一些工作,并且必须进行身份验证才能对网站执行POST请求。
The easiest way for me was to use basic authentication.
对我而言,最简单的方法是使用基本身份验证。
I was using Axios, so I set the Authorization
header to the POST request in this way:
我使用的是Axios,因此我以这种方式将Authorization
标头设置为POST请求:
const username = ''
const password = ''
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const url = 'https://...'
const data = {
...
}
axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})
翻译自: https://flaviocopes.com/axios-send-authorization-header/
怎么使用axios发送请求