我写了非常简单的服务器:
/* 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);
Run Code Online (Sandbox Code Playgroud)
我使用nodejs运行它.
现在我想写一个简单的客户端,使用ajax调用向服务器发送请求并打印响应(Hello World)
这里是clinet的javascript:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/" ,
success: function (data) {
console.log(data.toString);
}
});
Run Code Online (Sandbox Code Playgroud)
当我打开客户端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.
Run Code Online (Sandbox Code Playgroud)
我尝试添加到以下的ajax调用:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/" ,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
console.log(data.toString);
}
});
Run Code Online (Sandbox Code Playgroud)
但后来我明白了
Resource interpreted as Script but transferred with MIME type text/plain: "http://127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164".
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释我做错了什么,也许可以解决它?
非常感谢!
要克服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);
Run Code Online (Sandbox Code Playgroud)