发送带有授权标头的axios获取请求 [英] Sending axios get request with authorization header

查看:126
本文介绍了发送带有授权标头的axios获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用vue.js发送axios get请求,并且在不需要发送标头的情况下,它工作得很好.但是,当需要发送授权jwt时,出现了CORS错误:对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头."我不知道为什么会出现此问题,因为响应中有Access-Control-Allow-Origin:'*'标头.我的代码如下:

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:

axios.get(url, {
  headers: {
    'Authorization': 'Bearer TOKEN'
  }
})
.then(function (response) {
  console.log(response.data)
})

最奇怪的是,当我在标头上使用querystring.stringify或JSON.stringify时,我没有收到错误403(禁止),而只有错误401-未经授权.我尝试使用变量和令牌本身,但没有用.

The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.

我试图发送一个发布请求,以获取带有所需数据的Web令牌-用户名和密码,它可以正常工作.我能够获得令牌.

I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.

最近两天,我对此进行了大量研究,结果发现了不同种类的请求结构和配置,我尝试了所有这些请求结构和配置,但没有一个是有效的.有没有一种方法可以检查请求是否与标头一起发送?还有其他问题吗?如果有人可以提供帮助,我将不胜感激.谢谢.

I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.

推荐答案

我认为您应该将此代码添加到bootstrap.js(或定义axios的位置):

I think you should add this code to the bootstrap.js (or where the axios is defined):

window.axios = require('axios'); // I think its already added

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

您没有提到,但是我想您使用的是laravel或其他框架,这种框架可以防止csrf攻击,因此您需要将生成的令牌添加到ajax请求标头中.

You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.

这篇关于发送带有授权标头的axios获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆