简体   繁体   中英

Javascript Authorization HTTP Headers

I am currently trying to set up a POST request to an REST API (Cloudsight) with basic authorization. My code so far is:

 var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequestHeader("Authorization:", "CloudSight [key]"); xhr.setRequestHeader("Content-Type", "http://previews.123rf.com/images/valzann/valzann1412/valzann141200061/34262193-cigarette-end-on-a-white-background-Stock-Photo.jpg"); xhr.send(null); console.log(xhr.status); console.log(xhr.statusText); 

When I try and run it I get the error: Uncaught SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization:' is not a valid HTTP header field name.

Does anyone know what is wrong with the code? I am very new to Javascript and APIs but would very much appreciate an answer. (Here's the link to Cloudsight's documentation if it helps: https://cloudsight.readme.io I have looked through it and tried to find other Authorization HTTP Header Javascript examples without success.)

You don't need the : when supplying headers. Remove them from:

xhr.setRequestHeader("Authorization:", ...

The request now passes but returns some other error, which you have to handle on your part. I guess it wont be a problem.

This goes for every header, not only for Authorization . Hope this resolves your problem.

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