没有来自node.js的Ajax响应

时间:2017-06-18 04:08:43

标签: javascript node.js ajax express

我的Ajax请求未收到正确的响应!它总是进入readyState' 4'响应状态' 0' ??

客户代码:

<main>
  <div class="acrylic shadow">
    Acrylic material!
  </div>
  <div class="acrylic shadow">
    Acrylic material!
  </div>
</main>

<main>
  <div class="acrylic shadow">
    Acrylic material!
  </div>
  <div class="acrylic shadow">
    Acrylic material!
  </div>
</main>

<main>
  <div class="acrylic shadow">
    Acrylic material!
  </div>
</main>

服务器代码(Node.js + Express):

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
                    if(xhttp.readyState == 4 && xhttp.status == 200){
                        document.getElementById("lastNameLabel").innerHTML = "response recieved!"; 
                        const responseJSON = JSON.parse(xhttp.responseText);
                        if(responseJSON.emailTaken == "false"){
                            window.location = server+"/client/home.html";
                        }
                    }
                };
xhttp.open("POST", server+"/signUp", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("email="+email);

我知道我的服务器正在处理请求,因为我看到了url调用,但响应从未到达html客户端!!我是Super Stuck!

2 个答案:

答案 0 :(得分:0)

将@ jaromanda-x的suggestion作为答案,您需要在服务器中启用CORS。

这就是它的完成方式:

var cors = require('cors');

app.use(cors());

有关详细信息,请参阅this express doc

答案 1 :(得分:-1)

您必须让您的NodeJS服务器回复HTTP响应消息,其中包含状态代码和原因短语,例如

res.status(200).send({ status: 'ok' });
相关问题