阿里雲實現Serverless+ Express的服務端渲染

AWS通過lambda實現後端服務的serverless部署。阿里雲對標的函數計算也可以實現相應的功能。

預備知識:

  • nodejs
  • express
  • 阿里雲函數計算
  • 阿里雲API網關

實現:

一、 安裝依賴

首先我們需要初始化一個工程。

npm init

使用alicloud-serverless-express

npm install express  alicloud-serverless-express
二、

安裝完依賴後,我們需要開始編寫一個helloworld 代碼。
首先我們需要一個express實例

// app.js
const express = require('express')
const app = express()

app.get('/', function (req, res) {
      res.send('Hello World!')
})

//app.listen(8080);
module.exports = app;

然後我們需要通過alicloud-serverless-express來啓動express server。其中exports.handler是函數計算的入口函數。詳見 Nodejs 函數入口

// index.js
const alicloudServerlessExpress = require('alicloud-serverless-express');
const app = require('./app');
const server = alicloudServerlessExpress.createServer(app);
 
exports.handler = (event, context, callback) =>{
    try{
        event = JSON.parse(event.toString());
    }catch(err){
        console.log('local event')
    }
    alicloudServerlessExpress.proxy(server, event, callback);
}

在阿里雲的serverless express實現過程中。我們使用API 網關(以函數計算作爲API網關後端服務)暴露外部API, 使用函數計算命令行工具 fun實現API 網關和函數計算的一鍵部署。

三、 fun 部署

首先,需要編寫template.yml:
template.yml:

Resources:
  fc-demo:
    Type: 'Aliyun::Serverless::Service'
    Properties:
      Description: 'fc service '
    feedback: 
      Type: 'Aliyun::Serverless::Function'
      Properties:
        Handler: index.handler
        Runtime: nodejs8
        CodeUri: './'
        Timeout: 60
  apigateway_demo:
    Type: 'Aliyun::Serverless::Api'
    Properties:
      StageName: RELEASE
      DefinitionBody:
        '/':
          get: 
            x-aliyun-apigateway-api-name: demo 
            x-aliyun-apigateway-description: api gateway of demo
            x-aliyun-apigateway-request-config:
              requestMode: "PASSTHROUGH"
              requestProtocol: "http,https"
            x-aliyun-apigateway-visibility: PUBLIC
            x-aliyun-apigateway-fc:
              arn: acs:fc:::services/${fc-demo.Arn}/functions/${feedback.Arn}/
              timeout: 3000

注意,這裏的template.yml的存放路徑和函數計算的CodeUri: './'是具有直接聯繫的,當CodeUri'./'時,需要將template.ymlindex.js放在同級目錄下。
最後,在template.yml所在的目錄下執行:

fun deploy
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章