Developing an HTTP Function
Deploy the Koa framework by using an HTTP function. For details, see Creating an HTTP Function.
Prerequisites
- You have prepared a bootstrap file as the startup file of the HTTP function. Example:
/opt/function/runtime/nodejs14.18/rtsp/nodejs/bin/node $RUNTIME_CODE_ROOT/index.js
- /opt/function/runtime/nodejs14.18/rtsp/nodejs/bin/node: path of the Node.js compilation environment.
- $RUNTIME_CODE_ROOT: system variable that represents the /opt/function/code path for storing project code in a container.
- index.js: project file. You can also define a custom name.
Table 1 lists the supported Node.js versions and the corresponding paths.
Table 1 Node.js paths Language
Path
Node.js 6
/opt/function/runtime/nodejs6.10/rtsp/nodejs/bin/node
Node.js 8
/opt/function/runtime/nodejs8.10/rtsp/nodejs/bin/node
Node.js 10
/opt/function/runtime/nodejs10.16/rtsp/nodejs/bin/node
Node.js 12
/opt/function/runtime/nodejs12.13/rtsp/nodejs/bin/node
Node.js 14
/opt/function/runtime/nodejs14.18/rtsp/nodejs/bin/node
- Install the Node.js environment on a Linux host and prepare the Node.js project file.
- Create a project folder.
mkdir koa-example && cd koa-example
- Initialize the Node.js project and download the Koa framework. The node_modules folder and the package.json and package-lock.json files are created in the folder.
npm init -y npm i koa
- Create the index.js file to reference the Koa framework. For details about how to use this framework, see Koa's guide.
Sample code:
const Koa = require("koa"); const app = new Koa(); const main = (ctx) = >{ if (ctx.request.path == ("/koa")) { ctx.response.type = " application/json"; ctx.response.body = "Hello World, user!"; ctx.response.status = 200; } else { ctx.response.type = " application/json"; ctx.response.body = 'Hello World!'; ctx.response.status = 200; } }; app.use(main); app.listen(8000, '127.0.0.1'); console.log('Node.js web server at port 8000 is running..')
- HTTP functions can only use APIG or APIC triggers. According to the forwarding protocol between FunctionGraph and APIG/APIC, a valid HTTP function response must contain body(String), statusCode(int), headers(Map), and isBase64Encoded(boolean). By default, the response is encoded using Base64. The default value of isBase64Encoded is true. The same applies to other frameworks. For details about the constraints, see Base64 Decoding and Response Structure.
- By default, port 8000 is enabled for HTTP functions.
- Table 1 describes the context methods provided by FunctionGraph.
- Create a bootstrap file.
- Create a project folder.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.