vue ajax获取返回header,javascript - VueJs and VueResource, removing header fields from a Ajax request - ...

在Vue.js 2.2.6和vue-resource 1.2.1中,开发者遇到一个问题:全局设置的Authorization请求头在所有请求中被发送,包括向第三方API的请求,而该第三方API不允许使用此头。尝试通过设置headers为null或修改Access-Control-Allow-Headers未成功。在vue-resource文档中提到可以通过请求配置对象来覆盖默认设置,但文档不完整。使用拦截器可以编辑请求头,但无法删除特定字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When I instantiate a Vuejs (2.2.6) and Vue-resource (1.2.1), I set the header authorization with the following code, this way I can authorize all requests to my API:

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

However, I want to make a request for a third party API, and I do not want the Authorization field to be sent. Additionally, this API does not allow you to use this authorization header.

let CEP = '';

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json')

.then(response => {

console.log(response.headers);

});

This way the authorization field is sent with the header, on Access-Control-Request-Headers:

jZtQo.png

I tried to remove some header fields with the following codes, without success.

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

});

In the vue-resource documentation, there is the possibility of inserting an object to force the request configuration, but the documentation isn't complete.

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json', {

...here...

}).then(response => {

console.log(response.headers);

});

Is there any way to remove the Authorization field, or any other field from a given request?

Thanks.

* UPDATED *

By using the interceptors (as in the below sample) I can edit the request but I can not delete a particular field.

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

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

if (viacep) {

request.headers.set('AUTHORIZATION', 'TRY THIS');

}

next(response => {});

});

1Me9R.png

Try to Delete:

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

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

if (viacep) {

request.headers.delete('AUTHORIZATION');

}

next(response => {});

});

NONiM.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值