簡體   English   中英

如何設置header和axios中的選項?

[英]How to set header and options in 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)

做這件事有很多種方法:

  • 對於單個請求:

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

您可以發送帶有標頭的 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
  }
})

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

您可以將配置對象傳遞給 axios,例如:

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

這是正確的方法:-

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

這是一個帶有 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 是您要發送的數據。 它可以是一個值或一個數組。 (如果你想發送一個對象,你可能需要序列化它)

你可以初始化一個默認頭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)
        })

您還可以為每個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';

如果您想使用參數和標頭進行獲取請求。

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

試試這個代碼

在示例代碼中使用 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 標頭中進行了這樣的更改。 它工作正常。

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

在通過 axios 將其發送到我的 Django API 之前,我必須創建一個fd=new FormData()對象並使用[.append()][1]方法,否則我會收到 400 錯誤。 在我的后端,個人資料圖像通過 OneToOne 關系與用戶模型相關聯。 因此,它被序列化為一個嵌套對象,並期望這個 put 請求能夠工作。

對前端狀態的所有更改都是使用this.setState方法完成的。 我相信重要的部分是最后的 handleSubmit 方法。

首先我的 axios 提出請求:

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 后簽名

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){
     ....
     ....
   }
 }
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 的請求中一起使用參數和正文。

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

@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 請求將開始正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM