요청 핸들러를 사용하여 HTTP 요청을 통해 함수를 트리거할 수 있습니다. 이렇게 하면 GET, POST, PUT, DELETE, OPTIONS 등 지원되는 HTTP 메서드를 통해 함수를 호출할 수 있습니다.
추가 HTTP 옵션
옵션
설명
region
HTTP 함수는 단일 리전과 여러 리전을 지정할 수 있습니다. 여러 리전이 지정되면 리전별로 별도의 함수 인스턴스가 배포됩니다.
timeoutSeconds(Python의 경우 timeout_sec)
HTTP 함수에서 최대 1시간의 제한 시간을 지정할 수 있습니다.
cors
HTTP 함수가 CORS 정책을 지정할 수 있습니다. true로 설정하면 모든 출처가 허용되고, string, regex, array를 설정하면 허용된 출처를 지정할 수 있습니다. 명시적으로 설정하지 않으면 기본값은 false/CORS 정책 없음입니다.
CORS 구성(교차 출처 리소스 공유)
cors 옵션을 사용하여 함수에 액세스할 수 있는 출처를 관리하세요. 기본적으로 HTTP 함수에는 CORS가 구성되어 있지 않습니다. 즉, 함수에 관한 교차 출처 요청으로 인해 이 오류가 발생합니다.
request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
함수의 cors 옵션을 false로 설정하여 CORS를 명시적으로 사용 중지할 수도 있습니다.
일부 교차 출처 요청만 허용하려면 허용하는 특정 도메인 또는 정규 표현식의 목록을 전달하면 됩니다. 예를 들어 개발자가 firebase.com 및 flutter.com 도메인을 소유한 경우, firebase.com에 여러 하위 도메인이 있을 수 있으므로 cors 옵션을 [/firebase\.com$/, 'https://flutter.com'](Node.js의 경우) 또는 [r'firebase\.com$', r'https://flutter\.com'](Python의 경우)으로 설정해야 할 수 있습니다.
함수를 공개적으로 사용할 수 있어야 하는 경우(예: 공개 API 또는 웹사이트를 제공하는 경우) cors 정책을 true로 설정하세요.
HTTP 요청으로 함수 트리거
플랫폼의 요청 핸들러(onRequest() 또는 on_request)를 사용하여 HTTP 이벤트를 처리하는 함수를 만듭니다. 이 섹션의 예시는 함수 엔드포인트로 HTTP GET 요청을 보낼 때 트리거되는 '시간 서버' 샘플을 기반으로 합니다. 샘플 함수는 현재 서버 시간을 가져오고, URL 쿼리 매개변수에 지정된 대로 시간 형식을 지정하고, HTTP 응답으로 결과를 보냅니다.
요청 및 응답 객체 사용
요청 객체는 클라이언트에서 보낸 HTTP 요청 속성에 액세스할 수 있는 권한을 부여하고 응답 객체는 클라이언트로 응답을 다시 보내는 방법을 제공합니다.
@https_fn.on_request(cors=options.CorsOptions(cors_origins="*",cors_methods=["get","post"]))defdate(req:https_fn.Request)-> https_fn.Response:"""Get the server's local date and time."""
const{onRequest}=require('firebase-functions/v2/https');constexpress=require('express');constapp=express();// Add middleware to authenticate requestsapp.use(myMiddleware);// build multiple CRUD interfaces:app.get('/:id',(req,res)=>res.send(Widgets.getById(req.params.id)));app.post('/',(req,res)=>res.send(Widgets.create()));app.put('/:id',(req,res)=>res.send(Widgets.update(req.params.id,req.body)));app.delete('/:id',(req,res)=>res.send(Widgets.delete(req.params.id)));app.get('/',(req,res)=>res.send(Widgets.list()));// Expose Express API as a single Cloud Function:exports.widgets=onRequest(app);
Python
fromfirebase_adminimportinitialize_app,dbfromfirebase_functionsimporthttps_fnimportflaskinitialize_app()app=flask.Flask(__name__)# Build multiple CRUD interfaces:@app.get("/widgets")@app.get("/widgets/<id>")defget_widget(id=None):ifidisnotNone:returndb.reference(f"/widgets/{id}").get()else:returndb.reference("/widgets").get()@app.post("/widgets")defadd_widget():new_widget=flask.request.get_data(as_text=True)db.reference("/widgets").push(new_widget)returnflask.Response(status=201,response="Added widget")# Expose Flask app as a single Cloud Function:@https_fn.on_request()defhttpsflaskexample(req:https_fn.Request)-> https_fn.Response:withapp.request_context(req.environ):returnapp.full_dispatch_request()
HTTP 함수를 Firebase Hosting에 연결할 수 있습니다. Firebase Hosting 사이트의 요청은 특정 HTTP 함수로 프록시 처리될 수 있습니다. 이를 통해 HTTP 함수로 커스텀 도메인을 사용할 수도 있습니다. Cloud Functions를 Firebase Hosting에 연결하는 방법에 대해 자세히 알아보세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-09(UTC)"],[],[],null,["\u003cbr /\u003e\n\nYou can trigger a function through an HTTP request with a request\nhandler. This allows you to invoke a function through\nthe following supported HTTP methods: `GET`, `POST`, `PUT`, `DELETE`, and\n`OPTIONS`.\n\nAdditional HTTP options\n\n| Option | Description |\n|---------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `region` | HTTP functions may specify an array of regions as well as a single region. When multiple regions are specified, a separate function instance will be deployed for each region. |\n| `timeoutSeconds` (`timeout_sec` for Python) | HTTP functions may specify a timeout of up to one hour. |\n| `cors` | HTTP functions may specify CORS policies. You can set this to `true` to allow all origins or a `string`, `regex`, or `array` to specify allowed origins. Defaults to false/no CORS policies if not explicitly set. |\n\nConfiguring CORS (Cross-Origin Resource Sharing)\n\nUse the `cors` option to control which origins can\naccess your function. By default, HTTP functions don't have CORS configured,\nmeaning that any cross-origin request to your function results in this error: \n\n request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n\nYou can also explicitly disable CORS by setting the `cors` option to `false`\nfor your function.\n\nTo allow some cross-origin requests, but not all, you can pass a list of\nspecific domains or regular expressions that should be allowed. For example, if\nyou own the domains `firebase.com` and `flutter.com`, and `firebase.com` can\nhave many subdomains, you might want to set the `cors` option to\n`[/firebase\\.com$/, 'https://flutter.com']` for Node.js or\n`[r'firebase\\.com$', r'https://flutter\\.com']` for Python: \n\nNode.js \n\n const { onRequest } = require(\"firebase-functions/v2/https\");\n\n exports.sayHello = onRequest(\n { cors: [/firebase\\.com$/, \"https://flutter.com\"] },\n (req, res) =\u003e {\n res.status(200).send(\"Hello world!\");\n }\n );\n\nPython \n\n from firebase_functions import https_fn, options\n\n @https_fn.on_request(\n cors=options.CorsOptions(\n cors_origins=[r\"firebase\\.com$\", r\"https://flutter\\.com\"],\n cors_methods=[\"get\", \"post\"],\n )\n )\n def say_hello(req: https_fn.Request) -\u003e https_fn.Response:\n return https_fn.Response(\"Hello world!\")\n\nIf your function should be openly available, for example if it's serving a\npublic API or website, set the `cors` policy to `true`.\n\nTrigger a function with an HTTP request\n\nUse the request handler for your platform ([`onRequest()`](/docs/reference/functions/2nd-gen/node/firebase-functions.https#httpsonrequest)\nor [`on_request`](/docs/reference/functions/python/firebase_functions.https_fn#on_request))\nto create a function that handles HTTP events. Examples in this section are based on a\n\"time server\" sample that triggers when you send\nan HTTP `GET` request to the functions endpoint. The sample function\nretrieves the current server time, formats the time as specified in a URL query\nparameter, and sends the result in the HTTP response.\n\nUsing request and response objects\n\nThe request object gives\nyou access to the properties of the HTTP request sent by the client, and the\nresponse object gives you a way to send a response back to the client. \n\nNode.js \n\n```javascript\nexports.date = onRequest(\n {timeoutSeconds: 1200, region: [\"us-west1\", \"us-east1\"]},\n (req, res) =\u003e {\n// ...\n});\n```\n\nPython \n\n @https_fn.on_request(cors=options.CorsOptions(cors_origins=\"*\", cors_methods=[\"get\", \"post\"]))\n def date(req: https_fn.Request) -\u003e https_fn.Response:\n \"\"\"Get the server's local date and time.\"\"\" \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L41-L45\n\n| **Important:** Make sure that all HTTP functions terminate properly. By terminating functions correctly, you can avoid excessive charges from functions that run for too long.\n\nUsing existing Express or Flask apps\n\nUsing the app as the argument for\nthe request handler, you can pass a full app to an HTTP function: \n\nNode.js \n\n const { onRequest } = require('firebase-functions/v2/https');\n\n const express = require('express');\n const app = express();\n\n // Add middleware to authenticate requests\n app.use(myMiddleware);\n\n // build multiple CRUD interfaces:\n app.get('/:id', (req, res) =\u003e res.send(Widgets.getById(req.params.id)));\n app.post('/', (req, res) =\u003e res.send(Widgets.create()));\n app.put('/:id', (req, res) =\u003e res.send(Widgets.update(req.params.id, req.body)));\n app.delete('/:id', (req, res) =\u003e res.send(Widgets.delete(req.params.id)));\n app.get('/', (req, res) =\u003e res.send(Widgets.list()));\n\n // Expose Express API as a single Cloud Function:\n exports.widgets = onRequest(app);\n\nPython \n\n from firebase_admin import initialize_app, db\n from firebase_functions import https_fn\n import flask\n\n initialize_app()\n app = flask.Flask(__name__)\n\n # Build multiple CRUD interfaces:\n\n\n @app.get(\"/widgets\")\n @app.get(\"/widgets/\u003cid\u003e\")\n def get_widget(id=None):\n if id is not None:\n return db.reference(f\"/widgets/{id}\").get()\n else:\n return db.reference(\"/widgets\").get()\n\n\n @app.post(\"/widgets\")\n def add_widget():\n new_widget = flask.request.get_data(as_text=True)\n db.reference(\"/widgets\").push(new_widget)\n return flask.Response(status=201, response=\"Added widget\")\n\n\n # Expose Flask app as a single Cloud Function:\n\n\n @https_fn.on_request()\n def httpsflaskexample(req: https_fn.Request) -\u003e https_fn.Response:\n with app.request_context(req.environ):\n return app.full_dispatch_request() \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/http-flask/functions/main.py#L16-L48\n\nInvoke an HTTP function\n\nAfter you deploy an HTTP function, you can invoke it through its own unique\nURL. Use the exact URL output from the CLI after deployment.\n\nFor example, the URL to invoke `date()` looks like this: \n\n https://us-central1-\u003cproject-id\u003e.cloudfunctions.net/date\n\nWith Express and Flask app routing, the function name is added as a prefix to\nthe URL paths in the app you define.\n\nRead values from the request\n\nIn the `date()` function example, the function tests both the URL parameter and\nthe body for a `format` value to set the date/time format to use: \n\nNode.js \n\n```javascript\nlet format = req.query.format;\nformat = req.body.format;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/https-time-server/functions/index.js#L68-L68\n```\n\nPython \n\n format = req.args[\"format\"] if \"format\" in req.args else None \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L55-L55\n\nTerminate HTTP Functions\n\nAfter retrieving and formatting the server time, the `date()` function\nconcludes by sending the result in the HTTP response: \n\nNode.js\n\nAlways end an HTTP function with `send()`, `redirect()`,\nor `end()`. Otherwise, your function might continue to run and be\nforcibly terminated by the system. See also\n[Sync, Async and Promises](/docs/functions/terminate-functions). \n\n```javascript\nconst formattedDate = moment().format(`${format}`);\nlogger.log(\"Sending formatted date:\", formattedDate);\nres.status(200).send(formattedDate);https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/https-time-server/functions/index.js#L73-L75\n```\n\nPython \n\n formatted_date = datetime.now().strftime(format)\n print(f\"Sending Formatted date: {formatted_date}\")\n return https_fn.Response(formatted_date) \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L67-L69\n\nIntegrating with Firebase Hosting\n\nYou can connect an HTTP function to Firebase Hosting. Requests on your\nFirebase Hosting site can be proxied to specific HTTP functions. This also\nallows you to use your own custom domain with an HTTP function. Learn more about\n[connecting Cloud Functions to Firebase Hosting](/docs/hosting/functions)."]]