我使用Axios来执行如下的HTTP post:
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 post:
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)
当前回答
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://api.pexels.com/v1/curated',
params: {page: '2', per_page: '40'},
headers: {Authorization: '_authkey_'}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
其他回答
@user2950593 您的axios请求是正确的。您需要在服务器端允许您的自定义头。 如果你在php中有api,那么这段代码将为你工作。
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, header1");
一旦您允许在服务器端使用自定义头文件,axios请求就可以正常工作了。
您还可以为每个axios请求设置选定的头信息:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
config.headers.Authorization = 'AUTH_TOKEN';
return config;
});
第二种方法
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
使用异步/等待
Axios post签名 Post (url:字符串,数据?: any, config?: AxiosRequestConfig): Promise<AxiosResponse> data和config都是可选的 AxiosRequestConfig可以查看- https://github.com/axios/axios/blob/e462973a4b23e9541efe3e64ca120ae9111a6ad8/index.d.ts#L60
....
....
try {
....
....
const url = "your post url"
const data = {
HTTP_CONTENT_LANGUAGE: self.language
}
const config = {
headers: {
"header1": value
},
timeout: 1000,
// plenty more options can be added, refer source link above
}
const response = await axios.post(url, data, config);
// If Everything's OK, make use of the response data
const responseData = response.data;
....
....
}catch(err){
// handle the error
if(axios.isAxiosError(err){
....
....
}
}
你可以初始化一个默认头axios.defaults.headers
axios.defaults.headers = {
'Content-Type': 'application/json',
Authorization: 'myspecialpassword'
}
axios.post('https://myapi.com', { data: "hello world" })
.then(response => {
console.log('Response', response.data)
})
.catch(e => {
console.log('Error: ', e.response.data)
})
正确的方法是:- axios。Post ('url', {"body":data}, { 标题:{ “内容类型”:“application / json” } } )