我使用 Axios 执行这样的 HTTP 帖子:
import axios from 'axios'
params = {'HTTP_CONTENT_LANGUAGE': self.language}
headers = {'header1': value}
axios.post(url, params, headers)
这个对吗?或者我应该这样做:
axios.post(url, params: params, headers: headers)
我使用 Axios 执行这样的 HTTP 帖子:
import axios from 'axios'
params = {'HTTP_CONTENT_LANGUAGE': self.language}
headers = {'header1': value}
axios.post(url, params, headers)
这个对吗?或者我应该这样做:
axios.post(url, params: params, headers: headers)
做这件事有很多种方法:
对于单个请求:
let config = {
headers: {
header1: value,
}
}
let data = {
'HTTP_CONTENT_LANGUAGE': self.language
}
axios.post(URL, data, config).then(...)
设置默认全局配置:
axios.defaults.headers.post['header1'] = 'value' // for POST requests
axios.defaults.headers.common['header1'] = 'value' // for all requests
要在 axios 实例上设置为默认值:
let instance = axios.create({
headers: {
post: { // can be common or any other method
header1: 'value1'
}
}
})
//- or after instance has been created
instance.defaults.headers.post['header1'] = 'value'
//- or before a request is made
// using Interceptors
instance.interceptors.request.use(config => {
config.headers.post['header1'] = 'value';
return config;
});
您可以发送带有 Headers 的 get 请求(例如使用 jwt 进行身份验证):
axios.get('https://example.com/getSomething', {
headers: {
Authorization: 'Bearer ' + token //the token is a variable which holds the token
}
})
您也可以发送post请求。
axios.post('https://example.com/postSomething', {
email: varEmail, //varEmail is a variable which holds the email
password: varPassword
},
{
headers: {
Authorization: 'Bearer ' + varToken
}
})
我这样做的方法是设置这样的请求:
axios({
method: 'post', //you can set what request you want to be
url: 'https://example.com/request',
data: {id: varID},
headers: {
Authorization: 'Bearer ' + varToken
}
})
axios.post('url', {"body":data}, {
headers: {
'Content-Type': 'application/json'
}
}
)
您可以将配置对象传递给 axios,例如:
axios({
method: 'post',
url: '....',
params: {'HTTP_CONTENT_LANGUAGE': self.language},
headers: {'header1': value}
})
这是正确的方法:-
axios.post('url', {"body":data}, {
headers: {
'Content-Type': 'application/json'
}
}
)