在一個項目上想用NodeJS,在前端的JS(http://localhost/xxx)中ajax訪問後端RestAPI(http://localhost:3000/….)時(Chrome)報錯:javascript
XMLHttpRequest cannot load http://localhost:3000/auth/xxx/xxx. Originhttp://localhost is not allowed by Access-Control-Allow-Origin.前端
使用 Ajax Cross Origin - jQuery plugin ajax跨域請求 java
方案一:
Expressvar 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/vYBR3yweb
方案二:
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("開始監聽...");
});