我使用 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' // 对于 POST 请求 axios.defaults.headers.common['header1'] = 'value' // 对于所有请求
对于在 axios 实例上设置为默认值: let instance = axios.create({ headers: { post: { // 可以是 common 或任何其他方法 header1: 'value1' } } }) //- 或在创建实例之后实例.defaults.headers.post['header1'] = 'value' //- 或在发出请求之前 // 使用拦截器 instance.interceptors.request.use(config => { config.headers.post['header1'] = '值'; 返回配置; });
您可以发送带有标头的 get 请求(例如,使用 jwt 进行身份验证):
axios.get('https://example.com/getSomething', {
headers: {
Authorization: 'Bearer ' + token //the token is a variable which holds the token
}
})
您也可以发送发布请求。
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' } } )
header
是以单数还是复数声明的。从你的回答来看,这对我有帮助。
您可以将配置对象传递给 axios,例如:
axios({
method: 'post',
url: '....',
params: {'HTTP_CONTENT_LANGUAGE': self.language},
headers: {'header1': value}
})
这是正确的方法:-
axios.post('url', {"body":data}, { headers: { 'Content-Type': 'application/json' } } )
这是一个带有 headers 和 responseType 的简单配置示例:
var config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob'
};
axios.post('http://YOUR_URL', this.data, config)
.then((response) => {
console.log(response.data);
});
Content-Type 可以是 'application/x-www-form-urlencoded' 或 'application/json' 也可以是 'application/json;charset=utf-8'
responseType 可以是 'arraybuffer'、'blob'、'document'、'json'、'text'、'stream'
在本例中,this.data 是您要发送的数据。它可以是一个值或一个数组。 (如果你想发送一个对象,你可能需要序列化它)
您可以初始化默认标头 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
请求设置选定的标头:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
config.headers.Authorization = 'AUTH_TOKEN';
return config;
});
第二种方法
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
如果您想使用参数和标头进行获取请求。
var params = { paramName1: paramValue1, paramName2: paramValue2 } var headers = { headerName1: headerValue1, headerName2: headerValue2 } Axios.get(url, {params, headers} ).then(res =>{ console.log(res.data .representation); });
试试这个代码
在示例代码中使用 axios get rest API。
在安装
mounted(){
var config = {
headers: {
'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
'x-rapidapi-key': '5156f83861mshd5c5731412d4c5fp18132ejsn8ae65e661a54'
}
};
axios.get('https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats?
country=Thailand', config)
.then((response) => {
console.log(response.data);
});
}
希望是帮助。
我在发布请求中遇到了这个问题。我在 axios 标头中进行了这样的更改。它工作正常。
axios.post('http://localhost/M-Experience/resources/GETrends.php',
{
firstName: this.name
},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
在通过 axios 将它发送到我的 Django API 之前,我必须创建一个 fd=new FormData()
对象并使用 [.append()][1]
方法,否则我会收到 400 错误。在我的后端,个人资料图像通过 OneToOne 关系与用户模型相关联。因此,它被序列化为一个嵌套对象,并期望这个 put 请求能够工作。
前端中状态的所有更改都使用 this.setState
方法完成。我相信重要的部分是最后的 handleSubmit 方法。
首先我的 axios 提出请求:
export const PutUser=(data)=>(dispatch,getState)=>{
dispatch({type: AUTH_USER_LOADING});
const token=getState().auth.token;
axios(
{
¦ method:'put',
¦ url:`https://<xyz>/api/account/user/`,
¦ data:data,
¦ headers:{
¦ ¦ Authorization: 'Token '+token||null,
¦ ¦ 'Content-Type': 'multipart/form-data',
¦ }
})
¦ .then(response=>{
¦ ¦ dispatch({
¦ ¦ ¦ type: AUTH_USER_PUT,
¦ ¦ ¦ payload: response.data,
¦ ¦ });
¦ })
¦ .catch(err=>{
¦ ¦ dispatch({
¦ ¦ ¦ type:AUTH_USER_PUT_ERROR,
¦ ¦ ¦ payload: err,
¦ ¦ });
¦ })
}
我的 handleSubmit 方法需要创建以下 json 对象,其中图像属性被实际用户输入替换:
user:{
username:'charly',
first_name:'charly',
last_name:'brown',
profile:{
image: 'imgurl',
}
}
这是我在组件中的 handleSumit 方法:检查 append
handleSubmit=(e)=>{
¦ e.preventDefault();
¦ let fd=new FormData();
¦ fd.append('username',this.state.username);
¦ fd.append('first_name',this.state.first_name);
¦ fd.append('last_name',this.state.last_name);
¦ if(this.state.image!=null){fd.append('profile.image',this.state.image, this.state.image.name)};
¦ this.props.PutUser(fd);
};
使用异步/等待
axios post 签名 post(url: string, data?: any, config?: AxiosRequestConfig): Promise
....
....
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){
....
....
}
}
@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 请求将开始正常工作。
不定期副业成功案例分享
data
=>它将从我们正在使用的特定调用中覆盖您的实际身体部位。所以在这种情况下不使用。