تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
يمكنك تشغيل دالة من خلال طلب HTTP باستخدام معالج طلب. يتيح لك ذلك استدعاء دالة من خلال طرق HTTP المتوافقة التالية: GET وPOST وPUT وDELETE وOPTIONS.
خيارات HTTP الإضافية
Option
الوصف
region
يمكن أن تحدّد دوال HTTP صفيفًا من المناطق بالإضافة إلى منطقة واحدة. عند تحديد مناطق متعدّدة، سيتم نشر نسخة منفصلة من الدالة لكل منطقة.
timeoutSeconds (timeout_sec لـ Python)
يمكن أن تحدّد دوال HTTP مهلة تصل إلى ساعة واحدة.
cors
قد تحدّد دوال HTTP سياسات CORS. يمكنك ضبط هذا الخيار على true للسماح بجميع المصادر أو string أو regex أو array لتحديد المصادر المسموح بها. يتم ضبط القيمة تلقائيًا على "خطأ"/"لا توجد سياسات مشاركة الموارد المتعدّدة المصادر" في حال عدم ضبطها بشكل صريح.
ضبط إعدادات مشاركة الموارد المتعدّدة المصادر (CORS)
استخدِم الخيار cors للتحكّم في المصادر التي يمكنها الوصول إلى وظيفتك. بشكلٍ تلقائي، لا يتم ضبط CORS في دوال HTTP، ما يعني أنّ أي طلب من مصادر متعددة إلى دالتك سيؤدي إلى ظهور الخطأ التالي:
request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
يمكنك أيضًا إيقاف CORS بشكل صريح من خلال ضبط الخيار cors على false
للدالة.
للسماح ببعض الطلبات الواردة من مصادر متعددة، وليس كلها، يمكنك تمرير قائمة بنطاقات محددة أو تعبيرات عادية يجب السماح بها. على سبيل المثال، إذا كنت تملك النطاقَين firebase.com وflutter.com، وكان بإمكان firebase.com أن يتضمّن العديد من النطاقات الفرعية، قد تحتاج إلى ضبط الخيار cors على [/firebase\.com$/, 'https://flutter.com'] لـ Node.js أو [r'firebase\.com$', r'https://flutter\.com'] لـ Python:
إذا كان من المفترض أن تكون وظيفتك متاحة للجميع، مثلاً إذا كانت تعرض واجهة برمجة تطبيقات أو موقعًا إلكترونيًا متاحًا للجميع، اضبط السياسة 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."""
باستخدام التطبيق كوسيطة لمعالج الطلبات، يمكنك تمرير تطبيق كامل إلى دالة HTTP:
Node.js
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()
بعد استرداد وقت الخادم وتنسيقه، تنهي الدالة date() عملها
عن طريق إرسال النتيجة في استجابة HTTP:
Node.js
يجب دائمًا إنهاء دالة HTTP بالرمز send() أو redirect() أو end(). بخلاف ذلك، قد يستمر تنفيذ الدالة وقد يوقفها النظام بالقوة. راجِع أيضًا
المزامنة وغير المتزامنة والوعود.
تاريخ التعديل الأخير: 2025-09-06 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","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-06 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],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)."]]