1

I'm sending data to the server using JSON and post method, but I can't read the response from the server. Here's my code:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://staging.smartenupcs.com/api/v1/licenses/create", true);
xhr.setRequestHeader("Smartenup-API-KEY", "webflow.c407d56c5ab23115af0075+DzDMrMtWZENCoct9Pa7DUA54mIgP8c9o");
var jsonStr = JSON.stringify({
  "first_name": "Bla",
  "last_name": "Blabla",
  "email": "[email protected]",
  "product_name": "webflow_essentials",
  "order_id": 21811,
  "voucher": null

});
xhr.send(jsonStr);

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var myObj = JSON.parse(xhr.responseText);
    alert(myObj);
  }
};

I tried many options but no success.

I hope someone can help, thank you in advance

2
  • 1
    have you tried checking what "xhr.status" is? probably not 200? Commented Feb 24, 2019 at 23:33
  • Use the browsers debugging tools to inspect the network call being made and see if you're getting the response you expect. Commented Feb 24, 2019 at 23:58

3 Answers 3

1

There are no issues with the code.

The issue is with Cross-Origin Requests. You seems to be hitting API from domain other than staging.smartenupcs.com most probably localhost.

Just add cross-origin headers to server and it will work.

PS: It will work without cross-origin headers when your frontend code and api are hosted on same domain.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Please check at Server side for Access-Control-Allow-Origin header. Also check for OPTIONS preflight request of that api/action. After that check for api response status and your response checking condition.

Comments

0

I would recommend using fetch API instead of the XMLHttpRequest object.

function postData(url = `UR_URL_HERE`, data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.