使用Javascript读取JSON响应-问题

使用Javascript读取JSON响应-问题,javascript,json,xmlhttprequest,Javascript,Json,Xmlhttprequest,我使用JSON和post方法向服务器发送数据,但无法读取服务器的响应。这是我的密码: var xhr = new XMLHttpRequest(); xhr.open("POST", "https://staging.smartenupcs.com/api/v1/licenses/create", true); xhr.setRequestHeader("Smartenup-API-KEY", "webflow.c407d56c5ab23115af0075+DzDMrMtWZENCoct9Pa7

我使用JSON和post方法向服务器发送数据,但无法读取服务器的响应。这是我的密码:

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": "bla@gmail.com",
  "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);
  }
};
我尝试了许多选择,但没有成功


我希望有人能帮忙,提前谢谢你

请在服务器端查看
访问控制允许来源
标题。还要检查该api/操作的飞行前请求的
选项。然后检查api响应状态和您的响应检查条件。

代码没有问题

问题在于跨来源请求。您似乎是从域而不是
staging.smartenupcs.com
中访问API,很可能是本地主机

只需将跨源标题添加到服务器,它就可以工作了

PS:当前端代码和api托管在同一个域上时,它将在没有跨源标题的情况下工作


我建议使用fetch API而不是XMLHttpRequest对象

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
}

你试过检查“xhr.status”是什么吗?可能不是200?使用浏览器调试工具检查正在进行的网络调用,并查看是否得到预期的响应。