我是node.js/express的新手。我看到這個帖子(Allow CORS REST request to a Express/Node.js application on Heroku),但是提出的解決方案並不奏效。允許CORS REST請求到express/node.js應用程序
我只是打電話給mapquest API來獲取一些數據來玩。
這裏是我的server.js的一部分:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
console.log('hit options');
res.send(200);
}
else {
next();
}
};
app.configure(function(){
console.log('configuring app');
app.use(allowCrossDomain);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
//app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
/**
* Main route
*/
app.get('/', function (req, res, next) {
console.log("getting /");
Project.findAll()
.success(function (projects) {
res.render('index', { projects: projects });
})
.error(next);
});
這裏是我的客戶端main.js的一部分:
$('#spec').click(function(ev){
var form = $(this);
$.ajax({
url: "http://www.mapquestapi.com/geocoding/v1/address?key=<mykey>"
, type: 'POST'
, datatype: 'json'
, contentType: 'json'
, data: {
location : {
"postalCode":"99999"
}
, options : { thumbMaps : false}
}
, success: function(resp){
$('#mapdata').html(resp);
}
, error : function(resp){
$('#mapdata').html(resp);
}
});
});
以下是Chrome瀏覽器開發的窗口我的請求頭:
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:www.mapquestapi.com
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31
這裏是響應頭:
允許:TRACE,OPTIONS的Content-Length:0日期:孫老師,2013年4月7日3時18分48秒 GMT服務器:Apache-狼/ 1.1
,這裏是錯誤消息:
Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
服務器:Apache-Coyote/1.1是什麼?這不是一個正常的節點事情。你的應用程序是否在代理之後運行?如果是這樣,它可能會剝離這些標題。 – icktoofay 2013-04-07 03:56:34
不在apache代理後面運行......確實很奇怪 – 2013-04-07 23:42:18