CLASSFUNC BLOG

We Share Our Knowledge
Site Search

Tạo Api HTTP Cloud Functions với Express & Cors

Dương Đàm ✍︎︎ 21-09-2020

Github source code: https://github.com/duongdam/FirebaseFunctions-CallApi

Trước tiên, các bạn tạo 1 Http functions với dạng Http request

exports = module.exports = functions.https.onRequest((req, res) => {
  // ...
});

Cài đặt các gói npm install —save express cors

Ví dụ về việc cài đặt

const express = require('express');
const cors = require('cors');
const app = express();

// Automatically allow cross-origin requests
app.use(cors({ origin: true }));

// Add middleware to authenticate requests
app.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 = functions.https.onRequest(app);

Ví dụ về exports file từ thư mục khác trong môi trường node

const decoder = require('jwt-decode');
const moment = require('moment');
const getTokenFromHeader = require('../Actions/getTokenFromHeader');

const myMiddleware = (req, res, next) => {
  try {
    const accessToken = getTokenFromHeader(req);
    if (!accessToken)
      return res.status(400).send('AccessToken is missing');

    const userData = decoder(accessToken);
    if (moment(userData.exp * 1000).isBefore(moment().format()))
      return res.status(400).send('AccessToken is expired');

    return next();
  } catch (e) {
    console.log(e);
    return res.status(401).send('Login require!');
  }
};

exports = module.exports = myMiddleware;

Các request khác các bạn làm tương tự, tuỳ thuộc và api của bạn bảo mật mà thiết kế chức năng của functions myMiddleware theo yêu cầu của bạn nhé.

Configure hosting behavior:

Important: Firebase Hosting supports Cloud Functions in us-central1 only.

Full flow in firebase.json

{
  "hosting": {

    "public": "dist/app",  // "public" is the only required attribute for Hosting

    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],

    "redirects": [ {
      "source": "/foo",
      "destination": "/bar",
      "type": 301
    }, {
      "source": "/firebase/**",
      "destination": "https://www.firebase.com",
      "type": 302
    } ],

    "rewrites": [ {
      // Shows the same content for multiple URLs
      "source": "/app/**",
      "destination": "/app/index.html"
    }, {
      // Configures a custom domain for Dynamic Links
      "source": "/promos/**",
      "dynamicLinks": true
    }, {
      // Directs a request to Cloud Functions
      "source": "/bigben",
      "function": "bigben"
    }, {
      // Directs a request to a Cloud Run containerized app
      "source": "/helloworld",
      "run": {
        "serviceId": "helloworld",
        "region": "us-central1"
      }
    } ],

    "headers": [ {
      "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)",
      "headers": [ {
        "key": "Access-Control-Allow-Origin",
        "value": "*"
      } ]
    }, {
      "source": "**/*.@(jpg|jpeg|gif|png)",
      "headers": [ {
        "key": "Cache-Control",
        "value": "max-age=7200"
      } ]
    }, {
      "source": "404.html",
      "headers": [ {
        "key": "Cache-Control",
        "value": "max-age=300"
      } ]
    } ],
    "cleanUrls": true,
    "trailingSlash": false,
    // Required to configure custom domains for Dynamic Links
    "appAssociation": "AUTO",
  }
}

Tài liệu tham khảo: