在AJAX請求時出現 No 'Access-Control-Allow-Origin' header is present
當你的網頁在console顯示以下有關"Access-Control-Allow-Origin"的訊息,怎麼辦?
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxxxx.com' is therefore not allowed access.
老掉牙的跨來源 HTTP 請求(cross-origin HTTP request)問題,網上亦不難找到解決辦法,不過就為了方便自己將來腦退化所以以此為記。
要解決cross-origin HTTP request的問題,其中一個正當方法就是實行CORS (跨來源資源共享, Cross-Origin Resource Sharing)。
NodeJs的Server上,我喜歡以下這個處理方法(參考自Stackoverflow):app.use(function(req, res, next) {
var allowedOrigins = ['https://xxxxx.com', 'http://localhost:3000'];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin); }
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', true);
return next();
});