我写了非常简单的服务器:
/* 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".
任何人都可以解释我做错了什么以及如何解决它?
非常感谢!
答案 0 :(得分:5)
要克服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);
答案 1 :(得分:3)
第一个错误是由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);