gpt4 book ai didi

javascript - 在 header 中使用 token 获取请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:12 25 4
gpt4 key购买 nike

当我对地址“http://localhost:8080/clients”执行提取请求时,我需要帮助将 token 包含在 header 中'.

现在我收到这条消息“HTTP 403 Forbidden”。

授权 token 1234abcd

function getAllClients() {
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');

return fetch('http://localhost:8080/clients', {
method: 'GET',
mode: 'no-cors',
headers: myHeaders,
})
.then(response => response.json())
.then((user) => {
console.log(user.name);
console.log(user.location);
})
.catch((error) => {
console.error(error);
});
}

getAllClients();

最佳答案

使用fetch(),当启用no-cors 模式时,您不能发送Authorization header 。

no-cors — Prevents the method from being anything other than HEAD, GETor POST, and the headers from being anything other than simpleheaders.

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode

什么是简单 header ?

  • 接受
  • 接受语言
  • 内容语言
  • Content-Type,其值在提取后具有 MIME 类型(忽略参数),即 application/x-www-form-urlencodedmultipart/form-data,或text/plain

https://fetch.spec.whatwg.org/#simple-header

所以你的问题在下面一行:

mode: 'no-cors',

只需将其从获取请求中删除并像往常一样附加您的 Authorization header 。

const myHeaders = new Headers();

myHeaders.append('Content-Type', 'application/json');
myHeaders.append('Authorization', '1234abcd');

return fetch('http://localhost:8080/clients/', {
method: 'GET',
headers: myHeaders,
})

关于javascript - 在 header 中使用 token 获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48458116/

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