I want to call a secure Rest API using Javascript but its giving error.
the below code i am trying:
var request = new XMLHttpRequest();
var url = "http: // 10.10.50.10:8081/rsgateway/data/json/Number+9171246241";
var method = "GET";
request.open(method, url);
request.setRequestHeader("Access-Control-Allow-Headers", "*");
request.setRequestHeader("Access-Control-Allow-Credentials", "true");
request.setRequestHeader("Content-type", "application/json; charset=UTF-8");
request.setRequestHeader("Authorization", "Basic <test:Passw0rd@321 as Base64 encoded> ");
request.setRequestHeader("Access-Control-Allow-Origin", "*");
request.onreadystatechange = function () {
if (request.readyState ==4 && request.status ==200) {
var response = JSON.parse(this.response);
var sessionId = response.sessionId;
//Use this sessionId in all other calls
}
}
// Send request
console.log("OK");
request.send();
I am getting below errors in browser console:
XHROPTIONS
http :// 10.10.50.10:8081/rsgateway/data/json/Number+9171246241
CORS Missing Allow Origin
..........................................................................................................................................................
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.10.50.10:8081/rsgateway/data/json/Number+9171246241. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.
while i try to call the api using basic auth with the postman and using test user its working fine.
You are aware, that everyone can read your API credentials when you call the API from the client? This is normally a absolutely no go!
Are you sure the API is designed to accept requests from outside? Normally you get an CORS error if you try to fetch data from a server which only allow access from his own server or special whitelisted servers.
its an on premise service its ok, just i want to fix my JavaScript application to be able to call the api. if someone help/guide me, where i am doing wrong which i can not call successfully the api.
So you can easily compare the send headers from the postman console with the send headers in the browsers development tool and you will see the differentce
As i can see, postman is using client’s real ip address in request but my JavaScript is using 127.0.0.1 loopback ip address in request for Origin address. How can i hardcode Access-Control-Allow-Origin to the client’s real ip address ?
As sibertius has pointed out, this is a problem with the response coming out of the server, not what you’re sending to it. That’s the point of CORS. It isnt up to the requesting client what CORS headers are sent, its up to the server.
Postman ignores CORS because it’s a dev tool. Your browser doesnt, because it’s meant for production use.