2017-08-08 16 views
5

我用愛可信使POST請求如何在axios中設置標題和選項?

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

是coorect?

axios.post(url, params: params, headers: headers)是否正確?

回答

4

您可以通過配置對象像愛可信:

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

有幾種方法可以做到這一點:

  • 對於一個請求:

    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 
    
  • 有關愛可信例如設置爲默認值:

    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' 
    
1

你可以用頭髮送GET請求(認證與智威湯遜爲例):

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

我做這件事的方式是設置要求是這樣的:

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

您的第二篇文章請求未提供具體標題,您可以編輯它的完整示例嗎? – Striped

+0

這只是一個如何發送請求的例子。不一定非得與標題一致。如果你想發送標題,你可以看到第三個例子 –

1

這個例子很簡單,用頭+配置正確工作。

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); 
}); 
相關問題