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

use*_*593 100 vue.js axios

我使用axios来执行这样的HTTP帖子:

import axios from 'axios'
params = {'HTTP_CONTENT_LANGUAGE': self.language}
headers = {'header1': value}
axios.post(url, params, headers)
Run Code Online (Sandbox Code Playgroud)

它是否正确?或者我应该这样做:

__CODE__

riy*_*ali 186

做这件事有很多种方法:

  • 对于单个请求:

    let config = {
      headers: {
        header1: value,
      }
    }
    
    let data = {
      'HTTP_CONTENT_LANGUAGE': self.language
    }
    
    axios.post(URL, data, config).then(...)
    
    Run Code Online (Sandbox Code Playgroud)
  • 用于设置默认全局配置:

    axios.defaults.headers.post['header1'] = 'value' // for POST requests
    axios.defaults.headers.common['header1'] = 'value' // for all requests
    
    Run Code Online (Sandbox Code Playgroud)
  • 在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;
    });
    
    Run Code Online (Sandbox Code Playgroud)


rol*_*oli 89

您可以使用Headers发送get请求(例如,使用jwt进行身份验证):

axios.get('https://example.com/getSomething', {
 headers: {
   Authorization: 'Bearer ' + token //the token is a variable which holds the token
 }
})
Run Code Online (Sandbox Code Playgroud)

您也可以发送帖子请求.

axios.post('https://example.com/postSomething', {
 email: varEmail, //varEmail is a variable which holds the email
 password: varPassword
},
{
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})
Run Code Online (Sandbox Code Playgroud)

我这样做的方法是设置这样的请求:

 axios({
  method: 'post', //you can set what request you want to be
  url: 'https://example.com/request',
  data: {id: varID},
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 您的第二个帖子请求未提供特定标头,您可以编辑它以获取完整示例吗? (4认同)

小智 62

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


小智 24

这是正确的方法:-

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


小智 17

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

axios({
  method: 'post',
  url: '....',
  params: {'HTTP_CONTENT_LANGUAGE': self.language},
  headers: {'header1': value}
})
Run Code Online (Sandbox Code Playgroud)


gta*_*ero 12

这是带有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);
});
Run Code Online (Sandbox Code Playgroud)

Content-Type可以是'application/x-www-form-urlencoded'或'application/json',它也可以用'application/json; charset = utf-8'

responseType可以是'arraybuffer','blob','document','json','text','stream'

在此示例中,this.data是您要发送的数据.它可以是值或数组.(如果你想发送一个对象,你可能需要序列化它)


sup*_*rup 8

试试这个代码

在示例代码中使用 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);
  });
}
Run Code Online (Sandbox Code Playgroud)

希望是帮助。


Jso*_*owa 7

您还可以为每个axios请求设置选定的标头:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    config.headers.Authorization = 'AUTH_TOKEN';
    return config;
});
Run Code Online (Sandbox Code Playgroud)

第二种方法

axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
Run Code Online (Sandbox Code Playgroud)


Mor*_*s S 6

您可以初始化默认标题 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)
        })
Run Code Online (Sandbox Code Playgroud)


小智 6

如果要使用参数和标头进行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);
});
Run Code Online (Sandbox Code Playgroud)


Ern*_*nig 6

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

\n

前端内状态的所有更改都是通过该this.setState方法完成的。我相信重要的部分是最后的handleSubmit 方法。

\n

首先我的 axios put 请求:

\n
export const PutUser=(data)=>(dispatch,getState)=>{                                                                                                                                                                                                                                                                                                                                                                                                                                           \n    dispatch({type: AUTH_USER_LOADING});                                                                                                                                                                                                 \n    const token=getState().auth.token;                                                                                                                                                                                                                       \n    axios(                                                                                                                                                                                                                                                   \n    {                                                                                                                                                                                                                                                        \n    \xc2\xa6 method:\'put\',                                                                                                                                                                                                                                          \n    \xc2\xa6 url:`https://<xyz>/api/account/user/`,                                                                                                                                                                                           \n    \xc2\xa6 data:data,                                                                                                                                                                                                                                             \n    \xc2\xa6 headers:{                                                                                                                                                                                                                                              \n    \xc2\xa6 \xc2\xa6 Authorization: \'Token \'+token||null,                                                                                                                                                                                                                 \n    \xc2\xa6 \xc2\xa6 \'Content-Type\': \'multipart/form-data\',                                                                                                                                                                                                               \n    \xc2\xa6 }                                                                                                                                                                                                                                                      \n    })                                                                                                                                                                                                                                                       \n    \xc2\xa6 .then(response=>{                                                                                                                                                                                                                                      \n    \xc2\xa6 \xc2\xa6 dispatch({                                                                                                                                                                                                                                           \n    \xc2\xa6 \xc2\xa6 \xc2\xa6 type: AUTH_USER_PUT,                                                                                                                                                                                                                               \n    \xc2\xa6 \xc2\xa6 \xc2\xa6 payload: response.data,                                                                                                                                                                                                                            \n    \xc2\xa6 \xc2\xa6 });                                                                                                                                                                                                                                                  \n    \xc2\xa6 })                                                                                                                                                                                                                                                     \n    \xc2\xa6 .catch(err=>{                                                                                                                                                                                                                                          \n    \xc2\xa6 \xc2\xa6 dispatch({                                                                                                                                                                                                                                           \n    \xc2\xa6 \xc2\xa6 \xc2\xa6 type:AUTH_USER_PUT_ERROR,                                                                                                                                                                                                                          \n    \xc2\xa6 \xc2\xa6 \xc2\xa6 payload: err,                                                                                                                                                                                                                                      \n    \xc2\xa6 \xc2\xa6 });                                                                                                                                                                                                                                                  \n    \xc2\xa6 })                                                                                                                                                                                                                                                     \n  }      \n
Run Code Online (Sandbox Code Playgroud)\n

我的 handleSubmit 方法需要创建以下 json 对象,其中图像属性被实际的用户输入替换:

\n
user:{\nusername:\'charly\',\nfirst_name:\'charly\',\nlast_name:\'brown\',\nprofile:{\nimage: \'imgurl\',\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这是组件内我的 handleSumit 方法:\n检查追加

\n
handleSubmit=(e)=>{                                                                                                                                                                                                                                      \n\xc2\xa6 e.preventDefault();                                                                                                                                                                                                                                                                                                                                                                                                                  \n\xc2\xa6 let fd=new FormData();                                                                                                                                                                                                                                 \n\xc2\xa6 fd.append(\'username\',this.state.username);                                                                                                                                                                                                             \n\xc2\xa6 fd.append(\'first_name\',this.state.first_name);                                                                                                                                                                                                         \n\xc2\xa6 fd.append(\'last_name\',this.state.last_name);                                                                                                                                                                                                                                                                                                                                                                                                                  \n\xc2\xa6 if(this.state.image!=null){fd.append(\'profile.image\',this.state.image, this.state.image.name)};                                                                                                                                                                                                                                                                                                                                                        \n\xc2\xa6 this.props.PutUser(fd);                                                                                                                                                                                                                                \n}; \n
Run Code Online (Sandbox Code Playgroud)\n


Naj*_*thi 5

我在 post request 中遇到过这个问题。我在 axios 头文件中做了这样的改变。它工作正常。

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


小智 5

使用异步/等待

axios 帖子签名

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){
     ....
     ....
   }
 }
Run Code Online (Sandbox Code Playgroud)