What is CORS?
- 한마디로 Ajax를 사용할때 JSONP를 사용하지 않고 CrossDomain 통신을 할 수 있게 하는 것이다.
- http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
- https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
What is expressjs?
- nodejs에서 가장 유명한 Web Apllication Framework 다.
- http://expressjs.com/
How to?
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors()); // automatically supports pre-flighting
app.use(app.router);
app.get('/products/:id', function(req, res, next){ // didn't have to specify the cors() middleware here this time
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
How to authenticate?
CORS를 이용해서 인증을 사용하려면 추가적인 내용이 필요하다.
ServerSide
app.use(cors({
'origin' : 'http://localhost:10080',
'credentials' : true
}));
특히 인증을 사용할때에는 꼬옥 orgin을 명시해줘야 한다. '*'는 동작하지 않는다.
ClientSide
// angularjs $http
$http.post('http://cors-target-domain/auth/login', {
user : $scope.user,
pwd : $scope.pwd
}, {withCredentials : true}).success(function(data, status, headers, config) {
if(data.success) {
$rootScope.isLogin = true;
$rootScope.user = data.user;
$location.path('/').replace();
} else {
$window.alert("아이디와 패스워드가 잘못되었습니다. 다시 재로그인 부탁합니다.");
}
});
// angularjs resource
$resource('http://cors-target-domain/api/feed/:feedId', {feedId : '@id'}, {
query : {method : 'GET', withCredentials : true, isArray : true},
get : {method : 'GET', withCredentials : true},
save : {method : 'POST', withCredentials : true},
remove : {method : 'DELETE', withCredentials : true},
update : {method : 'PUT', withCredentials : true}
});
요청을 보낼때는 꼭 withCredentials : true
로 활성화 해야 한다.