阿里云实现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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章