简体   繁体   English

我的 API 没有收到我在 axios 上的访问令牌

[英]My API is not receiving my access token on axios

I'm using this code我正在使用此代码

const { status, data } = await axios({
    method,
    url,
    headers: {
      'Accept-Language': userInfo.locale,
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token.accessToken.jwtToken}`,
    },
    data: {
      requesterSubscription: token.accessToken.payload.sub,
      ...body,
    },
  });

But when I print what I'm receiving on the headers on the API I get:但是,当我在 API 的标题上打印收到的内容时,我得到:

  host: 'XXX.X.X.X:XXXX',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: '*/*',
  'access-control-request-method': 'POST',
  'access-control-request-headers': 'authorization,content-type',
  'access-control-request-private-network': 'true',
  origin: 'http://XXX.XXX.XX.X:XXXXX',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
  'sec-fetch-mode': 'cors',
  'sec-fetch-site': 'cross-site',
  'sec-fetch-dest': 'empty',
  referer: 'http://XXX.XXX.XX.X:XXXXX/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,fr;q=0.6,la;q=0.5'

So it isn't receiving my authorization and I'm getting errors because of it, there are no other possible places it could be making this request from.所以它没有收到我的授权,因此我收到了错误,没有其他可能的地方可以发出这个请求。

So First (1) question: Where do you store your access token?所以第一个(1)问题:你在哪里存储你的访问令牌?

  • In memory在 memory
  • In storage (localStorage or sessionStorage).在存储中(localStorage 或 sessionStorage)。 Bad practices Second (2) question: Do your retrieve data has requesterSubscription key?不良做法 第二 (2) 个问题:您的检索数据是否具有requesterSubscription键? Third: I hope your passing the the url and the method values?第三:我希望你通过urlmethod值?

Solution: I really recommend you to read axios docs .解决方案:我真的建议您阅读 axios文档 Also, it is better to create an export a axiosInstance (with a base config. Docs ), append interceptors on it for process before and after request.此外,最好在其上创建一个导出axiosInstance (带有基本配置。Docs )、append 拦截器,以便在请求之前和之后进行处理。 Tips:提示:

  • With the interceptors you can automatically append the token in the request header of your created instance (so you wont have to do it for further request).使用拦截器,您可以自动 append 您创建的实例的请求 header 中的令牌(因此您不必为进一步的请求执行此操作)。
  • Also check for your access token expiration and automatically ask for a new access token with a valid stored refresh token还要检查您的access token是否过期,并自动请求具有有效存储refresh token
  • Do not forget to configure CORS on your API server.不要忘记在您的 API 服务器上配置 CORS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM