我正在尝试学习 Node.js(创建 REST API 并从服务器发送消息)。所以我有一个关于从服务器发送响应到客户端的问题。当我从服务器端记录请求时,我看到了请求,但无法将消息发送到客户端。
我的 Node.js 服务器:
//handle a user request
function onRequest(request, response){
if(request.method =='GET' && request.url=='/'){
response.writeHead(200, {"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
console.log(request.url);
}
else if(request.method =='GET' && request.url=='/try'){
console.log("I am getting the request");
response.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow Origin":"*"});
response.write("test message");
response.end();
}
else{
console.log(request.url);
send404Response(response);
}
}
http.createServer(onRequest).listen(8888);
我的客户端功能:
function sendRequest(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.onreadystatechange==4 && xhttp.status == 200) {
alert("test alert") ;
}
}
xhttp.open("GET", "http://127.0.0.1:8888/try", true);
xhttp.send();
}
感谢任何帮助...提前致谢
最佳答案
我通过更改 if 语句解决了这个问题:
if (xhttp.onreadystatechange==4 && xhttp.status == 200)
收件人:
if (xhttp.readyState==4 && xhttp.status == 200)
关于javascript - 如何从 node.js 服务器获得简单的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251463/