【问题标题】:How to set header and options in axios?如何在axios中设置header和options?
【发布时间】:2023-03-18 10:47:01
【问题描述】:

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

【问题讨论】:

标签: javascript post axios


【解决方案1】:

有几种方法可以做到这一点:

  • 对于单个请求:

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

【讨论】:

    【解决方案2】:

    您可以发送带有标头的 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
      }
    })
    

    【讨论】:

    • 您的第二次发布请求未提供特定标头,您可以对其进行编辑以获取完整示例吗?
    • 通过在interceptors.request 中使用data =>它将覆盖我们正在使用的特定调用中的实际身体部分。所以在这种情况下不使用。
    • 你是否必须遵循'Authorization: 'Bearer' + token' 的标准,或者你可以做类似 Auth: token 之类的事情吗?我没有使用 auth0 api,而是在节点中自己做,如果愚蠢的问题是 jwt 和一般安全问题的新问题,我很抱歉
    【解决方案3】:

    axios.post('url', {"body":data}, {
        headers: {
        'Content-Type': 'application/json'
        }
      }
    )

    【讨论】:

    • 我很困惑header 是单数还是复数。从你的回答来看,这对我有帮助。
    【解决方案4】:

    您可以将配置对象传递给 axios,例如:

    axios({
      method: 'post',
      url: '....',
      params: {'HTTP_CONTENT_LANGUAGE': self.language},
      headers: {'header1': value}
    })
    

    【讨论】:

      【解决方案5】:

      这是正确的方法:-

      axios.post('url', {"body":data}, {
          headers: {
          'Content-Type': 'application/json'
          }
        }
      )

      【讨论】:

        【解决方案6】:

        这是一个带有 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 是您要发送的数据。它可以是一个值或一个数组。 (如果你想发送一个对象,你可能需要序列化它)

        【讨论】:

        • 你能解释一下在没有 config 关键字的情况下使用 our 设置标题的区别吗?
        • 使用配置变量生成更好、更易读的代码;没有别的@bubble-cord
        【解决方案7】:

        您可以初始化一个默认标头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)
                })
        

        【讨论】:

          【解决方案8】:

          如果您想使用参数和标头进行获取请求。

          var params = {
            paramName1: paramValue1,
            paramName2: paramValue2
          }
          
          var headers = {
            headerName1: headerValue1,
            headerName2: headerValue2
          }
          
           Axios.get(url, {params, headers} ).then(res =>{
            console.log(res.data.representation);
          });

          【讨论】:

            【解决方案9】:

            您还可以为每个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';
            

            【讨论】:

              【解决方案10】:

              试试这个代码

              在示例代码中使用 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);
                });
              }
              

              希望是帮助。

              【讨论】:

                【解决方案11】:

                我在发帖请求中遇到了这个问题。我在 axios 标头中进行了这样的更改。它工作正常。

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

                【讨论】:

                  【解决方案12】:

                  在通过 axios 将其发送到我的 Django API 之前,我必须创建一个 fd=new FormData() 对象并使用 [.append()][1] 方法,否则我会收到 400 错误。 在我的后端,个人资料图像通过 OneToOne 关系与用户模型相关联。因此,它被序列化为一个嵌套对象,并期望这个 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);                                                                                                                                                                                                                                
                  }; 
                  

                  【讨论】:

                    【解决方案13】:

                    使用异步/等待

                    axios 发布签名

                    post(url: string, data?: any, config?: AxiosRequestConfig): Promise 数据和配置都是可选的

                    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){
                         ....
                         ....
                       }
                     }
                    

                    【讨论】:

                      【解决方案14】:

                      @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 请求将开始正常工作。

                      【讨论】:

                      • OP 要求的是 nodejs,而不是 php,只是说
                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-09-21
                      • 2020-01-21
                      • 2018-04-10
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-06-12
                      • 2017-10-28
                      相关资源
                      最近更新 更多