-1

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.

  • Possible duplicate of [Why my $.ajax showing "preflight is invalid redirect error"?](https://stackoverflow.com/questions/33645511/why-my-ajax-showing-preflight-is-invalid-redirect-error) – Adam Chubbuck Oct 15 '18 at 00:25

1 Answers1

0

You mention that you need to send the token as a header, but in your example, you are sending it as part of the payload. Try the below:

xhr.setRequestHeader("x-auth-token", "<THE_AUTH_TOKEN>");

Adam Chubbuck
  • 1,612
  • 10
  • 27
  • Hey, in the first xmlhttprequest i need to send it as a payload, in the body to which i will get a response(The auth token) and i send it back as a header to another API URL. Sorry if it was confusing – Vishal Chauhan Oct 14 '18 at 23:48