AJAX 跨域 :Access-Control-Allow-Origin

在一个项目上想用NodeJS,在前端的JS(http://localhost/xxx)中ajax访问后端RestAPI(http://localhost:3000/….)时(Chrome)报错:

XMLHttpRequest cannot load http://localhost:3000/auth/xxx/xxx. Originhttp://localhost is not allowed by Access-Control-Allow-Origin.

本地测试解决方案:

  1. 使用Chrome插件:Allow-Control-Allow-Origin: *
  2. 为Chrome浏览器添加启动属性:   --disable-web-security

jQuery解决方案:

使用 Ajax Cross Origin - jQuery plugin ajax跨域请求 

NodeJS解决方案:

  • 方案一:Express
var express = require('express');
var app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});

app.get('/auth/:id/:password', function(req, res) {
res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');
var express = require('express');
var app = express();

app.get('/auth/:id/:password', function(req, res) {
res.header("Access-Control-Allow-Origin", "*"); //设置跨域访问
res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');

参考: 
http://m.blog.csdn.net/blog/marujunyy/8852017 
http://www.tuicool.com/articles/vYBR3y

  • 方案二:
var http=require("http");
var server=http.createServer(function(req,res){
if(req.url!=="/favicon.ico"){
res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"http://localhost:1234"});
res.write("你好啊!");
}
res.end();
});
server.listen(3000,"localhost",function(){
console.log("开始监听...");
});
var http=require("http");
var server=http.createServer(function(req,res){
if(req.url!=="/favicon.ico"){
//res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"http://localhost:1234"});
res.statusCode=200;
res.sendDate=false;
res.setHeader("Content-Type","text/plain");
res.setHeader("Access-Control-Allow-Origin","http://localhost:63342");
res.write("你好啊!");
}
res.end();
});
server.listen(3000,"localhost",function(){
console.log("开始监听...");
});

参考: 
http://www.jb51.net/article/57874.htm

posted @ 2015-08-29 22:12 Mr.Leo 阅读(...) 评论(...) 编辑 收藏