我怎样才能从node.js服务器获得简单的响应?

我正在尝试学习Node.js(创buildREST API并从服务器发送消息)。 所以我有一个关于从服务器发送响应到客户端的问题。 当我从服务器端logging请求时,我看到请求,但是我不能发送消息到客户端。

我的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:

 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) 

尝试将“Access-Control-Allow-Origin”添加到您的响应标题中:

这是一个解释CORS的链接: http ://www.html5rocks.com/en/tutorials/cors/

感谢更新。 您似乎遇到了跨域请求臭名昭着的问题…这是一个安全问题,粗略地说,浏览器不会允许从一个网站加载页面发出到另一个网站的AJAX请求。

换句话说, 它关乎你的浏览器如何打开发出ajax请求的html 。 如果页面本身是通过“ http://127.0.0.1:8888/index.html ”(其中index.html有一些button或任何可以发出ajax的页面)获得的,那么就可以。 如果你的最终目的确实是将静态页面部署在同一个服务器+端口上,那么dynamic回复就可以了。 如果你的意思是要把它们部署在不同的机器/端口上,你可能需要考虑CORS …