【问题标题】:why can't I set some headers on Request object?为什么我不能在 Request 对象上设置一些标头?
【发布时间】:2019-09-12 11:41:58
【问题描述】:

我正在尝试请求一个需要使用令牌进行身份验证的 REST API。在构造 Request 对象时,一些标头会消失。 为什么我不能设置我的授权标头?

let http_headers = {
        "Content-type": "application/json",
        'Authorization': 'Token token='+my_token,
        'Accept': 'Application/json'
    };

let url = this.base_url + '/api/v1/test';
let init =  {
            method: "POST",
            headers: new Headers(http_headers),
            mode: 'no-cors',
            credentials: 'omit' // I try that, but it doesn't seem to have effect
        };
let req = new Request( url, init );
console.log(req.headers.get("Accept")); // Application/json
console.log(req.headers.get("Authorization")); // null, why ?

【问题讨论】:

  • 什么是Request?是this module吗?或者this one?您使用的是 Node.js 还是浏览器?当您使用一些 Request 对象而不是 fetch 时,为什么会标记为 fetch-api
  • 你说mode: 'no-cors', - 这是一个跨域请求吗?还是同源请求?
  • @Quentin 这是来自 fetch API 的请求:developer.mozilla.org/en-US/docs/Web/API/Request。我最初(并打算)使用 fetch(url,init)。该网址来自另一个域。
  • 你在哪里定义my_token

标签: javascript fetch-api request-headers


【解决方案1】:

您可能想要使用 fetch 函数并在 options 参数中设置标题。

fetch(url, { //fetch options
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json",
            // Your headers here
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(); // parse response

借自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch 函数返回一个 Promise,其中包含 Response 对象,其中包含来自您的 api 的数据。

【讨论】:

  • 我使用了 Request,因为 Fetch 不起作用,而且我没有得到调试信息。 (并且捕获错误不起作用)如前所述,我还有另一个要调查的 pb。谢谢。
【解决方案2】:

请参阅mode 的文档

no-cors防止方法不是 HEAD、GET 或 POST,标头不是简单标头。如果任何 ServiceWorkers 拦截了这些请求,它们可能不会添加或覆盖除简单标头之外的任何标头。此外,JavaScript 可能不会访问结果响应的任何属性。这可确保 ServiceWorker 不会影响 Web 的语义,并防止因跨域泄露数据而引起的安全和隐私问题。

将模式设置为same-origincors 以允许设置凭据。

【讨论】:

  • 谢谢,所以我有另一个 pb。我之前添加了“no-cors”,因为我认为它是 pb。我会更深入地检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2018-11-22
  • 2012-12-26
  • 2014-09-22
  • 2012-03-24
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多