简体   繁体   English

Ajax响应不是来自node.js

[英]Ajax response not coming through from node.js

My Ajax request is not receiving proper response! 我的Ajax请求未收到正确的响应! It always enters readyState '4' with response status '0' ?? 它始终输入带有响应状态“ 0”的readyState“ 4”?

Client Code: 客户代码:

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);

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

app.post('/signUp', (req, res) => {
    res.end("it worked!!");
});

I Know my Server is processing the request since I see the url call, but the response never reaches the html client!!. 我知道我的服务器正在处理请求,因为我看到了url调用,但是响应从未到达html客户端!! I'm Super Stuck! 我好棒!

Putting @jaromanda-x's suggestion as an answer, you need to enable CORS in your server. 以@ jaromanda-x的建议作为答案,您需要在服务器中启用CORS。

This is how it's done: 这是这样做的:

var cors = require('cors');

app.use(cors());

For more info, refer this express doc about it. 有关更多信息,请参考此快速文档

您必须让NodeJS服务器使用HTTP响应消息进行回复,该HTTP响应消息包括状态码和原因短语,例如

res.status(200).send({ status: 'ok' });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM