0

I am not able to make a post-call using xmlhttprequest in javascript. First, I am getting a 401 response code from server-side. Below is code I am using below code.

function makeRestCall(){
        console.log("Rest call made")
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
        };

        xhttp.open("POST", "myurk", false, 'username', 'password');
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.send()
        alert(xhttp.status);
        alert(xhttp.responseText)

I am also getting

"Request has been blocked by CORS policy"

I am able to do a rest call from postman and using basic auth and getting response also

I have referred various links for making a rest call using javascript.

Link 1 Link 2

But still, I am not able to resolve the error. Can anyone tell what is wrong am I doing.

shv22
  • 680
  • 5
  • 28
  • That error means your server (the one you send the `POST` request to) doesn't support Cross-Domain requests. You have to either configure it to do so, or contact someone who can. – Ayrton Oct 15 '19 at 13:19
  • So why 401 error is coming? – shv22 Oct 15 '19 at 13:19
  • Is your server running Laravel to provide an API? – Ayrton Oct 15 '19 at 13:20
  • I don't think so – shv22 Oct 15 '19 at 13:23
  • Then my guess is your server is unable to authenticate your request (hence the 401 error) and then it tries to redirect you to another url which is not configured to use CORS (hence the CORS error). You have to either configure CORS on the redirect url, or ditch it entirely – Ayrton Oct 15 '19 at 13:24
  • so there is nothing wrong with the code? – shv22 Oct 15 '19 at 14:14
  • The code itself is fine, any problems you might have are configuration-wise. I'd recommend you not to make your XMLHttpRequests synchronous, though. It's better to make it async and wrap it with a Promise. – Ayrton Oct 15 '19 at 14:16

0 Answers0