在标头中使用令牌获取请求

per*_*nja 3 javascript fetch fetch-api

当我在地址' http:// localhost:8080/clients ' 上执行获取请求时,我需要帮助在标头中包含令牌.

现在我收到此消息"HTTP 403 Forbidden".

授权令牌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();
Run Code Online (Sandbox Code Playgroud)

Nim*_*mal 10

使用时fetch(),您无法Authorizationno-cors启用模式时发送标头.

no-cors - 防止该方法不是HEAD,GET或POST,而且标题不是简单标题.

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

什么是简单的标题?

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type和其值,萃取一次,具有MIME类型(忽略参数)也就是application/x-www-form-urlencoded, multipart/form-datatext/plain

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

所以你的问题在于以下几行:

mode: 'no-cors',
Run Code Online (Sandbox Code Playgroud)

只需将其从获取请求中删除并Authorization像往常一样追加标题.

const myHeaders = new Headers();

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

return fetch('http://localhost:8080/clients/', {
  method: 'GET',
  headers: myHeaders,
})
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)


Har*_*hal 6

有多种方法可以在请求中设置标头,您可以在此处查看文档。

这是更新的代码:

function getAllClients() {
const myHeaders = new Headers({
    'Content-Type': 'application/json',
    'Authorization': 'your-token'
});

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

.then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error('Something went wrong on api server!');
    }
  })
  .then(response => {
    console.debug(response);
  }).catch(error => {
    console.error(error);
  });
}

getAllClients();
Run Code Online (Sandbox Code Playgroud)