为什么我不能在请求 object 上设置一些 headers?

why can't I set some headers on Request object?

我正在尝试请求休息 API 需要使用令牌进行身份验证。在构造Requestobject时,一些header消失了。 为什么我不能设置授权 header?

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 ?

请参阅 mode

的文档

no-corsPrevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

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

您可能想使用获取功能并在选项参数中设置 headers。

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

提取函数 returns 一个 Promise,其响应 object 包含来自您的 api.

的数据