【发布时间】:2014-11-03 20:52:41
【问题描述】:
我写了非常简单的服务器:
/* 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".
谁能解释我做错了什么以及如何解决?
非常感谢!
【问题讨论】: