如何在axios中设置标题和选项?

时间:2017-08-08 22:16:55

标签: vue.js axios

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

14 个答案:

答案 0 :(得分:134)

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

  • 对于单个请求:

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

答案 1 :(得分:56)

  

您可以使用标头发送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
  }
})

答案 2 :(得分:22)

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

答案 3 :(得分:14)

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

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

答案 4 :(得分:10)

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

答案 5 :(得分:6)

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

答案 6 :(得分:5)

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

答案 7 :(得分:5)

尝试此代码

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

希望是帮助。

答案 8 :(得分:4)

我在发帖请求中遇到了这个问题。我在axios标头中做了这样的更改。很好。

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

答案 9 :(得分:2)

在通过 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);                                                                                                                                                                                                                                
}; 

答案 10 :(得分:1)

这是正确的方法:

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

答案 11 :(得分:0)

如果要使用参数和标头进行get请求。

var params = {
  paramName1: paramValue1,
  paramName2: paramValue2
}

var headers = {
  headerName1: headerValue1,
  headerName2: headerValue2
}

 Axios.get(url, {params, headers} ).then(res =>{
  console.log(res.data.representation);
});

答案 12 :(得分:-2)

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

答案 13 :(得分:-92)

Axios可以通过以下任何方式使用:

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

然后发布帖子请求:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

在使用axios进行ajax调用之前,不要忘记导入axios库