Hosted Node.js Server
Using HTTP access + cloud functions makes it easy to host Node.js server-side programs.
Preparations
- Prepare a basic project directory. Refer to Quick Start - Initialize Directory
Creating a Simple Hello World
In the working directory, execute the following commands to create the simplest Node.js Server:
mkdir functions/server && touch functions/server/index.js && touch functions/server/package.json
The content of
functions/server/index.js` is as follows:
// functions/server/index.js
const serverless = require("serverless-http");
exports.main = serverless((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
});
Tip
Here we use serverless-http to convert integration requests into IncomingMessage that can be received by a Node.js Server, while converting the returned ServerResponse into integration responses
The content of
functions/server/package.json` is as follows:
{
"name": "my-serverless-server",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"serverless-http": "^2.3.0"
}
}
Publish
Publish Cloud Function:
cloudbase fn deploy server
Create route:
cloudbase service create -p server -f server
Then you can access the Node.js Server via https://${env}.service.tcloudbase.com/server
:
curl https://${env}.service.tcloudbase.com/server
Hello World