상세 컨텐츠

본문 제목

CORS in expressjs

프로그래밍/스크립트

by 라제폰 2014. 9. 13. 11:02

본문

원문 : http://blog.niceilm.net/150176636784

What is CORS?

What is expressjs?

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로 활성화 해야 한다.

관련글 더보기