gpt4 book ai didi

javascript - 使用 fetch 或 axios 发送身份验证 header

转载 作者:行者123 更新时间:2023-12-03 02:00:21 25 4
gpt4 key购买 nike

如何使用 fetchaxios 发送身份验证 header ?

我尝试这样做,但在我的客户端没有任何具有身份验证值的 header 。

这是我的代码示例。

let myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Access-Control-Allow-Origin", "*");

let req = {
method: "GET",
headers: myHeaders,
mode: "no-cors",
credentials: "same-origin",
}
fetch('http://localhost:5000/secret', req)
.then(res => console.log(res))
.catch(err => console.log(err))

我尝试在我的 node.js 代码上检查它。

router.route("/").get(passportJWT, SecretController.secret);

最佳答案

要使两个来源被视为“相同”,它们必须共享:

  • 方案(例如 https)
  • 主机名
  • 端口

您正在从 http://localhost:3000http://localhost:5000 发出请求,因此正在发出跨域请求。

credentials: "same-origin"

...但您已将凭据(例如授权)限制为同源请求。

mode: "no-cors",

要通过跨域请求发送凭据,您必须通过 CORS 获得许可。

您不得设置no-cors

你需要

mode: "cors",
credentials: "include"

关于javascript - 使用 fetch 或 axios 发送身份验证 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com