node.js/express No Access-Control-Allow-Origin header CORS

북마크 추가

다른 ip / 도메인의 nodejs 서버를  ajax 호출 하려고 하면 

 

main:1 XMLHttpRequest cannot load http://localhost:3000/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

 

위와같은 에러가 발생한다. 

 

1.해결방법 

 

app.js에 아래의 코드를 추가한다. 

 

app.all('*',function(req,res,next){

    if (!req.get('Origin')){

        return next();

    }

    res.set('Access-Control-Allow-Origin','*');

    res.set('Access-Control-Allow-Methods','GET,POST');

    res.set('Access-Control-Allow-Headers','X-Requested-With,Content-Type');

    if ('OPTIONS' == req.method){

         return res.send(200);

    }

    next();

});

 

* 코드 위치는 router 설정이나 .get .post 보다 위에 있어야 합니다.

 

ex)

 

app.all('*',function(req,res,next){

    if (!req.get('Origin')){

        return next();

    }

    res.set('Access-Control-Allow-Origin','*');

    res.set('Access-Control-Allow-Methods','GET,POST');

    res.set('Access-Control-Allow-Headers','X-Requested-With,Content-Type');

    if ('OPTIONS' == req.method){

         return res.send(200);

    }

    next();

});

 

app.use('/', routes);
app.use('/users', users);

 

 

AD
관리자
2016-07-05 16:57
SHARE