【问题标题】:I have Authorization Bearer set in Fetch API but there is no Authorization in my Request Headers我在 Fetch API 中设置了授权承载,但我的请求标头中没有授权
【发布时间】:2020-04-03 22:21:34
【问题描述】:

这里是代码

fetch('http://localhost:3000/tasks/', {
    method: 'GET',
    mode: 'no-cors',
    headers: new Headers({
      'Authorization':
        'Bearer <jwt_token>'
    }),
    redirect: 'follow'
  })
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

令牌正在工作。我使用 Postman、php 中的 curl 和 nodeJS 对其进行了测试,一切正常。我总是得到回应。但使用这是我的反应应用程序,我得到的只是错误 401,这意味着我未经授权。在devtools的Networks选项卡中查看请求后,发现没有Authorization。

请求标头:

GET /tasks/ HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
Sec-Fetch-Dest: empty
Accept: */*
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: no-cors
Referer: http://localhost:3001/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,ja-GB;q=0.8,ja;q=0.7,en-US;q=0.6

我的获取代码有问题吗?还是反应有问题?我不知道。请发送帮助。

【问题讨论】:

  • 因为“no-cors”

标签: javascript reactjs


【解决方案1】:

为跨域请求设置 Authorization 标头需要 CORS 的许可。

您说:mode: 'no-cors' 禁用了浏览器中与 CORS 相关的所有内容,因此它无法获得权限并且不会抛出错误(而是静默失败)。

不要那样做。

【讨论】:

  • 但是当我删除 no-cors 模式时,我得到以下信息:CORS 策略已阻止从源 'localhost:3001' 获取在 'localhost:3000/tasks' 处的访问:对预检请求的响应不'不通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。我该怎么办?
  • @joshua — 正如我所说,它需要 CORS 的许可。服务器没有授予该权限。更改服务器以使其正常运行。
  • 谢谢。我必须先阅读 CORS,然后才能完全理解它们。按照这个medium.com/@dtkatz/… 修复它
【解决方案2】:
    fetch('http://localhost:3000/tasks/', {
      method: 'GET',
      mode: 'no-cors',
      headers: { 'Authorization':'Bearer <jwt_token>' },
      redirect: 'follow'
    })
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 2018-04-26
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多