我写了很简单的服务器:简单的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".
任何人都可以解释我做错了什么,也许如何解决它?
非常感谢!
谢谢你的答案,但我能怎么送修改的index.html到客户端,如果index.html的内容是动态的,并且每次请求都应该不同? – Farseer 2014-09-10 09:33:14
我提供的例子非常基础。它假设你的内容被静态存储在一个文件中。当然,您可以提供动态内容,这些内容可能基于来自远程服务器(如数据库或远程Web服务)的某些数据。你所要做的就是动态构建内容。我建议你看看[Express](http://expressjs.com)Node.js框架,它允许你在那里提供[模板文件](http://expressjs.com/guide.html#template-engines)是动态内容的占位符。准备好动态内容后,您可以将其提供给模板引擎。 – Eye 2014-09-10 09:38:00
模板引擎+ Express将正确呈现您的动态内容并提供给客户端。 – Eye 2014-09-10 09:38:27