ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Firebase cors 문제 해결하기
    개발 이야기/Firebase 2019. 2. 14. 18:04


    Firebase로 Host 중인 사이트에 도메인을 지정함.



    Firebase의 Cloud Function을 쓰면 cors 이슈가 나옴. 




    1. 먼저 firebase로 호스팅중인 소스의 firebase.json 파일에 크로스 도메인 이슈를 해결하기 위한 

    헤더를 추가함. headers 부분임.


    {
    "hosting": {

    "public": "public",
    "ignore": [
    "firebase.json",
    "**/.*",
    "**/node_modules/**"
    ],
    "headers": [ {
    "source" : "**",
    "headers" : [ {
    "key" : "Access-Control-Allow-Origin",
    "value" : "*"
    }]
    }]
    }
    }




    2. 작업중인 firebase의 함수 프로젝트의 functions 폴더로 이동해서 아래 명령어 실행


    npm install cors --save


    그럼 자동으로 함수 프로젝트의 package.json 파일의 dependencies에 cors가 추가됨.


    {
    "name": "functions",
    "description": "Cloud Functions for Firebase",
    "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
    },
    "dependencies": {
    "cors": "^2.8.5",        <==이렇게 추가됨.
    "firebase-admin": "~7.0.0",
    "firebase-functions": "^2.2.0"
    },
    "private": true
    }



    3. 클라우드 함수를 작성하는 index.js파일에 cors 추가


    const cors = require('cors')({
    origin: true
    });




    4. 클라우드 함수의 호출 방식에 따라서 cors 적용 유무가 다름


    onRequest 함수의 경우 cors를 처리해야함. (브라우저에서 ajax를 이용해서 get, post 방식으로 함수를 실행하는 경우)


    exports.helloWorld = functions.https.onRequest((request, response) => {
    cors(request, response, ()=>{
    response.send("Hello from Firebase!");
    });
    });


    onCall 함수의 경우 cors 처리를 하면 안됨. (브라우저에서 firebase function객체로 호출하는경우)


    exports.helloWorld2 = functions.https.onCall((data, context) => {
    return {msg:"Hello from Firebase!"};
    });



    위의 규칙이 꼬이면 internal 에러나 cors에러가 계속 남.



    댓글

Designed by Tistory.