FLYNNLABAboutMeCodingActivityStudy 2024초등수학
CORS in expressjs
expressjs, cors

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