简体   繁体   中英

I am trying to add authorization header in AJAX call using pure JavaScript. But gives error

Here is my code snippet:

var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Authorization", "Basic " + sessionStorage.getItem("token"));

It gives me error like:

core.js:1633 ERROR DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

You need to call .open(..) before setting the request headers.

This response was paste from this previous question here

So open it but do it before setting RequestHeader, like this:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'example link);
xhr.setRequestHeader ("Authorization", "Basic " + sessionStorage.getItem("token"));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM