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

你可以传递一个配置对象给axios,比如:

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

有几种方法可以做到:

For a single request: let config = { headers: { header1: value, } } let data = { 'HTTP_CONTENT_LANGUAGE': self.language } axios.post(URL, data, config).then(...) For setting default global config: axios.defaults.headers.post['header1'] = 'value' // for POST requests axios.defaults.headers.common['header1'] = 'value' // for all requests For setting as default on axios instance: 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; });

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

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

你也可以发送一个post请求。

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

这是一个简单的配置头和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

在这个例子中,这个。数据就是你想要发送的数据。它可以是一个值或数组。(如果你想发送一个对象,你可能需要序列化它)

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

如果你想用参数和头来做一个get请求。

这是瓦尔 paramName1: paramValue1 paramName2: paramValue2 …… 瓦尔希德斯 headerName1: headerValue1 headerName2: headerValue2 …… Axios。输入url然后(res = >—— console.log (res.data.representation); 新程序);

正确的方法是:- axios。Post ('url', {"body":data}, { 标题:{ “内容类型”:“application / json” } } )

试试这段代码

在示例代码中使用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 header中做了如下更改。它工作得很好。

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

axios。Post ('url', {"body":data}, { 标题:{ “内容类型”:“application / json” } } )

@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请求就可以正常工作了。

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

对前端状态的所有更改都是使用this完成的。设置状态的方法。我认为最重要的部分是最后的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方法: 检查附加

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请求设置选定的头信息:

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

第二种方法

axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';

使用异步/等待

Axios post签名 Post (url:字符串,数据?: 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){
     ....
     ....
   }
 }
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);
});

可以在axios请求中同时使用参数和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)); 
  }