简单的ajax请求到localhost nodejs服务器

我写了非常简单的服务器:

/* Creating server */ var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World\n"); }); /*Start listening*/ server.listen(8000); 

我使用nodejs来运行它。

现在我想编写简单的客户端,使用Ajax调用发送请求到服务器和打印响应(Hello World)

这里的clinet的javascript:

 $.ajax({ type: "GET", url: "http://127.0.0.1:8000/" , success: function (data) { console.log(data.toString); } }); 

当我打开客户端的HTML文件,我在控制台中得到以下错误:

 XMLHttpRequest cannot load http://127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

我尝试添加到ajax电话以下:

  $.ajax({ type: "GET", url: "http://127.0.0.1:8000/" , dataType: 'jsonp', crossDomain: true, success: function (data) { console.log(data.toString); } }); 

但是,然后我得到

 Resource interpreted as Script but transferred with MIME type text/plain: "http://127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164". 

任何人都可以解释我做错了什么,也许如何解决它?

非常感谢!

第一个错误是由CORS (跨源资源共享)策略引起的。 所有浏览器都规定,除非远程服务器通过Access-Control-Allow-OriginAccess-Control-Allow-Origin ,否则您不能向AJAX中的远程服务器发送请求,除非从当前服务器加载脚本/页面。

我build议从同一个Node.js服务器提供页面。 然后它会工作。 例如,当请求到达根/页面时,然后服务于index.html文件,否则服务器不pipe你想要的其他内容。

 var http = require('http'), fs = require('fs'); /* Creating server */ var server = http.createServer(function (request, response) { if (request.url == '/' || request.url == '/index.html') { var fileStream = fs.createReadStream('./index.html'); fileStream.pipe(response); } else { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World\n"); } }); /*Start listening*/ server.listen(8000); 

为了克服CORS,在你的node.js文件中根据你的需要写下面的内容:

 // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (eg in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true);