2017-04-05 109 views
5

去除報頭字段當我實例化一個Vuejs (2.2.6)和Vue的資源(1.2.1),我設置用下面的代碼的標題授權,這種方式我可以授權給我的API的所有請求:VueJs和VueResource,從Ajax請求

Vue.http.headers.common.AUTHORIZATION = 'BEARER ...'; 

不過,我想爲第三方API的請求,我不希望被髮送的Authorization領域。此外,此API不允許您使用此授權標頭。

let CEP = ''; 

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json') 
    .then(response => { 
     console.log(response.headers); 
    }); 

這樣的授權字段與所述頭中發送,上訪問控制請求報頭

Request header

我試圖刪除一些報頭字段用以下代碼,沒有成功。

this.$http.headers.common.AUTHORIZATION = null; 
this.$http.headers.common['Access-Control-Allow-Headers'] = null; 

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json') 
    .then(response => { 
     console.log(response.headers); 
    }); 

vue-resource文檔,有插入對象來強制請求配置的可能性,但文檔是不完整的。

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json', { 
    ...here... 
}).then(response => { 
    console.log(response.headers); 
}); 

有沒有辦法從給定的請求刪除授權場,或任何其他方面?
謝謝。

*更新*

通過使用攔截器(如下面的示例中)我可以編輯我無法刪除特定字段的請求,但

Vue.http.interceptors.push((request, next) => { 

    const viacep = request.url.includes('viacep.com.br'); 

    if (viacep) { 
     request.headers.set('AUTHORIZATION', 'TRY THIS'); 
    } 

    next(response => {}); 
}); 

editing request

嘗試刪除:

Vue.http.interceptors.push((request, next) => { 

    const viacep = request.url.includes('viacep.com.br'); 

    if (viacep) { 
     request.headers.delete('AUTHORIZATION'); 
    } 

    next(response => {}); 
}); 

enter image description here

回答

7

使用interceptor,檢查請求,並根據需要刪除標題。

Vue.http.interceptors.push(function(request, next) { 

    const removeAuthHeaders = request.url.includes("viacep.com.br"); 

    if (removeAuthHeaders){ 
    request.headers.delete('Access-Control-Allow-Headers') 
    request.headers.delete('AUTHORIZATION') 
    } 
    else { 
    request.headers.set('Access-Control-Allow-Headers', <value>) 
    request.headers.set('AUTHORIZATION', <value>) 
    } 
    next(); 
}); 
+0

這是令人難以置信的,我可以設置/修改,但我不能刪除! –

+1

@ThiagoPereira我認爲這可能是因爲你將它們分配給'.common'。你能不*做到這一點,只是像上面那樣分配它們? – Bert

+0

攔截器內部的'request.headers.common'是'undefined',我使用你的例子,當我嘗試刪除這個記號時什麼都沒有發生。請參閱上面的照片。你認爲這是錯誤的:'Vue.http.headers.common.AUTHORIZATION ='持票人:...';' –