I'm trying to request a rest API that needs authentication with a token. When constructing the Request object, some headers disappear. Why can't I set my Authorization 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 ?
See the documentation for mode
no-cors
— Prevents 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.
Set the mode to same-origin
or cors
to allow credentials to be set.
You probably want to use the fetch function and set the headers in the options parameter.
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
Borrowed from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
The fetch function returns a Promise that will have the Response object containing data from your api.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.