我编写了非常简单的服务器:
/* 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".
任何人都可以解释我做错了什么以及如何解决它?
非常感谢!
最佳答案
要克服 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);
关于ajax - 向本地主机nodejs服务器发送简单的ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25761481/