如何在axios中设置头部和选项?

445

我使用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)

1
https://axios-http.com/docs/req_config - Archmede
16个回答

8

我在Post请求中遇到了这个问题。我已经在axios头部进行了更改,现在它正常工作。

axios.post('http://localhost/M-Experience/resources/GETrends.php',
      {
        firstName: this.name
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });

6

我需要创建一个fd=new FormData()对象,并在通过axios发送到我的Django API之前使用[.append()][1]方法,否则我将收到400错误。 在我的后端中,个人资料图像通过一对一关系与用户模型相关联。因此,它被序列化为嵌套对象,并期望在put请求中使用该对象。

前端所有状态的更改都是使用this.setState方法完成的。 我认为最重要的部分是handleSubmit方法。

首先是我的axios put请求:

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);                                                                                                                                                                                                                                
}; 

5

使用 Async/Await

Axios post 签名

post(url: string, data?: 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){
     ....
     ....
   }
 }

3
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);
});

1
目前你的回答写得不够清晰。请[编辑]并添加更多细节来协助其他人理解这如何解答了所提出的问题。你可以在帮助中心找到更多有关如何书写好回答的信息。 - Community

1

你可以使用axios在请求中同时使用params和body。

  sendAllData (data) {
        axios
        .post(API_URL + "receiveData", JSON.stringify(data), {
          headers: { "Content-Type": "application/json; charset=UTF-8" },
          params: { mail: xyx@example.col }, //Add mail as a param
        })
        .then((response) => console.log("repsonse", response.status)); 
  }

-9

@user2950593 你的axios请求是正确的。你需要在服务器端允许自定义头部。 如果你的API是用PHP编写的,那么这段代码适用于你。

header("Access-Control-Allow-Origin: *");   
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, header1");

一旦在服务器端允许自定义标头,您的axios请求将开始正常工作。


OP 询问的是 Node.js,而不是 PHP,只是说一下。 - 钟智强

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接