使用 Header 中的令牌获取请求

Fetch request with token in Header

当我在地址“http://localhost:8080/clients”上执行提取请求时,我需要帮助将令牌包含在 header 中。

我现在收到这条消息 "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();

嗯,这就是你需要的:

 function getAllClients() {
  const myHeaders = new Headers();

  /* 
    myHeaders.append('Content-Type', 'application/json'); 
    since it's a get request you don't need to specify your content-type
  */

  myHeaders.append('Authorization', 'Token 1234abcd');

  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();

有多种方法可以在请求中设置header,可以查看文档here

这是更新后的代码:

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();

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

no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers.

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

什么是简单的header?

  • Accept
  • Accept-Language
  • Content-Language
  • 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,
})