Javascript 使用 Header 中的令牌获取请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48458116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:07:31  来源:igfitidea点击:

Fetch request with token in Header

javascriptfetchfetch-api

提问by peronja

I need help to include token in the header when I'm doing fetch request on address 'http://localhost:8080/clients'.

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

Right now I'm getting this message "HTTP 403 Forbidden".

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

Authorization Token 1234abcd

授权令牌 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();

回答by Nimeshka Srimal

With fetch(), you cannot send Authorizationheader when the no-corsmode is enabled.

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

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

no-cors — 防止方法是 HEAD、GET 或 POST 之外的任何内容,并且标题不能是简单标题之外的任何内容。

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

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

What are simple headers?

什么是简单的标题?

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Typeand whose value, once extracted, has a MIME type (ignoring parameters) that is application/x-www-form-urlencoded, multipart/form-data, or text/plain
  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type和其值,萃取一次,具有MIME类型(忽略参数)也就是application/x-www-form-urlencodedmultipart/form-datatext/plain

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

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

So your problem is in the following line:

所以你的问题是在以下行:

mode: 'no-cors',

Just drop it from the fetch request and append your Authorizationheader as usual.

只需将它从 fetch 请求中删除并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,
})

Hope it helps :)

希望能帮助到你 :)

回答by Fabien Greard

Well this is what you need :

那么这就是你所需要的:

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

回答by Harvey

There are multiple methods you can set the header in the request, you can check the documentation here.

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

Here is updated code:

这是更新的代码:

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