I am trying to get response from an API that sits behind an authentication layer. I first need to POST a request using a json request something like this.
{"username":"apitest",
"password":"testapi@321"
}
Lets assume that the api url is http://test-oms-test-staging.com.au/test/auth
I get back a json response that has the following in response body:
"token": "abcdefghabcdefgh"
Now I need to pass the token as a header "x-auth-token": into API that has parameters in it to get a response which needs to be displayed in the html page.
So far, i have been able to do the following
function begin() {
var xhr = new XMLHttpRequest();
var url = "http://test-oms-test-staging.com.au/test/auth";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
var string = json['token'];
console.log(string);
}
}
var data = JSON.stringify({"username": "apitest", "password":
"testapi@321"});
xhr.send(data);
}
Now when i query the second API URL with the response token in the header, i am getting the following error.
Response for preflight is invalid (redirect)
I do appologise if my request is too broad or not detailed enough, I am very new with programming. I did a bit of research and found out that my request is being re-directed because of the server security. Am I doing the right thing treating this as two individual methods? Thank-you again.
EDIT This is happening because the API is triggering an OPTIONS request which needs to be authenticated. I am thinking it is because I am doing this as two individual requests(First to POST Request to retrive the token in Response Body and Second 'GET' to pass the token as a header. In the second request the Pre-flight is triggered which sends an OPTION Request which is beign authenticated That is why I am now getting 401 'Unauthenticated' error. In the link provided for possible duplication, there are no answers besides editing the server to "Not Authenticate" which is not a valid solution.