您的请求应该发送到服务器,而不是实例化它的server.js文件。因此,该请求应如下所示:
xmlhttp.open("GET","http://localhost:8001/", true);此外,您正在尝试为前端(index.html)提供服务,并以相同的URI提供AJAX请求。为此,您将必须在server.js中引入逻辑,以区分AJAX请求和常规http访问请求。为此,您将需要引入GET / POST数据(即callhttp://localhost:8001/?getstring=true
),或者对AJAX请求使用不同的路径(即callhttp://localhost:8001/getstring
)。然后,在服务器端,您需要检查请求对象以确定在响应上写什么。对于后一种选项,您需要使用“ url”模块来解析请求。您正在正确调用,
listen()
但错误地编写了响应。首先,如果您希望在导航到http:// localhost:8001 /时提供index.html ,则需要使用response.write()
或将文件内容写入响应中response.end()
。首先,您需要包括fs=require('fs')以访问文件系统。然后,您需要实际提供文件。如果您异步使用XMLHttpRequest,则需要指定一个回调函数(已完成,第三个参数= true),并且想对响应做一些事情。您现在拥有的方式
string
将是undefined
(或可能是null
),因为该行将在AJAX请求完成之前执行(即responseText仍然为空)。如果同步使用它(第三个参数= false),则可以编写内联代码。不建议这样做,因为它会在请求期间锁定浏览器。异步操作通常与onreadystatechange函数一起使用,该函数一旦完成就可以处理响应。您需要学习XMLHttpRequest的基础知识。从 这里 开始。
这是一个包含以上所有内容的简单实现:
server.js:
var http = require('http'), fs = require('fs'), url = require('url'), choices = ["hello world", "goodbye world"];http.createServer(function(request, response){ var path = url.parse(request.url).pathname; if(path=="/getstring"){ console.log("request recieved"); var string = choices[Math.floor(Math.random()*choices.length)]; console.log("string '" + string + "' chosen"); response.writeHead(200, {"Content-Type": "text/plain"}); response.end(string); console.log("string sent"); }else{ fs.readFile('./index.html', function(err, file) { if(err) { // write an error response or nothing here return; } response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(file, "utf-8"); }); }}).listen(8001);console.log("server initialized");前端(index.html的一部分):
function newGame(){ guessCnt=0; guess=""; server(); displayHash(); displayGuessStr(); displayGuessCnt();}function server(){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","http://localhost:8001/getstring", true); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){string=xmlhttp.responseText; } } xmlhttp.send();}您需要对AJAX感到满意。使用mozilla学习中心学习XMLHttpRequest。使用基本的XHR对象后,您很可能希望使用一个良好的AJAX库,而不是手动编写跨浏览器的AJAX请求(例如,在IE中,您将需要使用ActiveXObject而不是XHR)。jQuery中的AJAX非常好,但是如果您不需要
更新:我在上面的代码中已更改
response.sendHeader()为新
response.writeHead()代码!!!



