原标题:Serverless 应用开发指南: Node.js 编程返回动态 HTML
在我们进行 Serverless + SPA 应用开发之前,先看看官方的相应 DEMO。serverless install -u https://github.com/serverless/examples/tree/master/aws-node-serve-dynamic-html-via-http-endpoint -n node-serve-html
然后执行部署serverless deploy
serverless.yml 文件,如下:# Serving HTML through API Gateway for AWS Lambdaservice: node-serve-htmlframeworkVersion: ">=1.1.0 <2.0.0"provider:
name: aws
runtime: nodejs4.3functions:
landingPage:
handler: handler.landingPage
events:
- http:
method: get
path: landing-page
对应的,我们的 handler.js 文件:'use strict';module.exports.landingPage = (event, context, callback) => { let dynamicHtml = '
Hey Unknown!
'; // check for GET params and use if available if (event.queryStringParameters && event.queryStringParameters.name) {dynamicHtml = `
Hey ${event.queryStringParameters.name}!
`;} const html = `
h1 { color: #73757d; }
Landing Page
${dynamicHtml}
`; const response = { statusCode: 200, headers: { 'Content-Type': 'text/html',
}, body: html,
}; // callback is sending HTML back
callback(null, response);
};
上面的代码所做的就是,当我们对 landing-page 发出请求的时候,便执行上面的 landingPage 代码。然后返回对应的 HTML body、statusCode、headers。
相应的部署日志如下:..............................
Serverless: Stack update finished...
Service Information
service: node-serve-html
stage: dev
region: us-east-1stack: node-serve-html-dev
api keys:
None
endpoints: GET - https://uocym5fe3m.execute-api.us-east-1.amazonaws.com/dev/landing-page
functions:
landingPage: node-serve-html-dev-landingPageLanding Page
Hey phodal!