2014-09-10 112 views
1

我写了很简单的服务器:简单的Ajax请求到本地主机服务器的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调用发送请求到服务器和打印响应(你好世界)

这里客户为例的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". 

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

非常感谢!

回答

2

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

我建议从相同的Node.js服务器提供页面。然后它会工作。例如,当请求进入根目录/页面时,则服务于index.html文件,否则服务器无论您想要什么其他内容。

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

谢谢你的答案,但我能怎么送修改的index.html到客户端,如果index.html的内容是动态的,并且每次请求都应该不同? – Farseer 2014-09-10 09:33:14

+0

我提供的例子非常基础。它假设你的内容被静态存储在一个文件中。当然,您可以提供动态内容,这些内容可能基于来自远程服务器(如数据库或远程Web服务)的某些数据。你所要做的就是动态构建内容。我建议你看看[Express](http://expressjs.com)Node.js框架,它允许你在那里提供[模板文件](http://expressjs.com/guide.html#template-engines)是动态内容的占位符。准备好动态内容后,您可以将其提供给模板引擎。 – Eye 2014-09-10 09:38:00

+0

模板引擎+ Express将正确呈现您的动态内容并提供给客户端。 – Eye 2014-09-10 09:38:27

4

为了克服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 (e.g. in case you use sessions) 
res.setHeader('Access-Control-Allow-Credentials', true); 
+0

如果你有兴趣,请查看这个好帖子http://techslides.com/client-side-javascript-to-node-js,相信你可以从中学到一些新东西 – 2015-01-22 13:26:06

相关问题