Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Hosts Nodejs Server


May 22, 2021 Mini Program Cloud Development Advanced



First, the basics of Nodejs Server

1, the basic HTTP server

As long as you have a Node environment installed locally or on the server, you can create a server using the require('http') method by introducing the http module. For example, let's use VS Code to create .js file (saved on your computer wherever you go), and then enter the following code:

  1. const http = require('http'); //引入内置的http模块
  2. const hostname = '127.0.0.1';
  3. const port = 3000;
  4. const requestHandler = (req, res) => { //
  5. res.statusCode = 200;
  6. res.setHeader('Content-Type', 'text/html;charset=utf-8');
  7. res.end('Node Server创建成功啦');
  8. console.log(`请求链接是:${req.url},请求方法是:${req.method}`)
  9. }
  10. const server = http.createServer(requestHandler) //使用 http.createServer() 方法创建服务器
  11. server.listen(port, hostname, () => { //listen为createServer返回对象的方法,用于指定HTTP服务器监听的端口号
  12. console.log(`通过此链接访问服务器 http://${hostname}:${port}/`);
  13. });

After saving, right-click the file in VS Code to open in the terminal, and then enter the following code in the terminal of VS Code to execute on Enter:

  1. node app.js

Entering http://127.0.0.1:3000/ browser gives you access to the server we created, and the page shows that Node Node Server创建成功啦 was created successfully, so it's easy to create an HTTP server with Nodejs.

Note that requestHandler has two parameters, req is the request request object, call the request object can get all the information of the HTTP request, such as request.url to get the request path; The requestHandler function is triggered every time the user visits (e.g. refreshing the page), and we can also see the printed logs at the terminal.

2, file server

With the fs module: The file directory can be created, deleted, queried, and read and written to and from files, as well as the url module: the URL can be processed and resolved, and we can send files from the server to the client. For example, we can modify the code .js the app as follows:

  1. var http = require('http');
  2. var url = require('url');
  3. var fs = require('fs');
  4. http.createServer( (req, res) => { //这里把上面的requestHandler给整到一起了,注意一下
  5. const requrl = url.parse(req.url, true);
  6. const filename = "." + requrl.pathname; //这里的.表示的是相对路径
  7. fs.readFile(filename, function(err, data) {
  8. if (err) {
  9. res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
  10. return res.end("404 页面没有找到");
  11. }
  12. res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  13. res.write(data);
  14. console.log(`请求链接是:${req.url},请求方法是:${req.method}`);
  15. return res.end();
  16. });
  17. }).listen(3000);

Then execute node app.js terminal (if you're still executing the node server before, you can terminate the server twice in a row by pressing Ctrl-C, and then perform the node app .js). Put a file such as tcb .jpg the same directory .js app, enter the following address in the browser (i.e. the path to the ip address plus file) to see:

  1. http://127.0.0.1:3000/tcb.jpg

When debugging locally, both the server and the client are the same computer, and http://127.0.0.1:3000/ to access the files in the server through the browser.

Second, host Nodejs Server

Can the cloud function build a Nodejs server, combined with cloud access and cloud functions, you can easily host Nodejs server-side programs. H ere you will use the serverless-http module. We can use serverless-http to convert integration requests into IncommingMessage that Node.js Server can receive, and to convert the returned ServerResponse into integration requests.

Use VS Code to create a new cloud function in the fusions folder, such as server, three new files like the cloud function developed by the small program cloud, and the assats folder, which holds various static resources such as HTML files, pictures, etc. that we want to return, as follows:

  1. ├── server //server云函数目录
  2. └── assets
  3. └── index.html
  4. └── demo.jpg
  5. └── index.js
  6. └── config.json
  7. └── package.json

and add serverless-http dependency to package.json,

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "serverless-http": "latest"
  4. }

Then enter the following code .js index server, and we'll turn over the code from the previous Nodejs Server, noting that it's different from normal cloud functions and integration request writing.

  1. const cloud = require('wx-server-sdk')
  2. const url = require('url')
  3. const fs = require('fs')
  4. cloud.init({
  5. env: cloud.DYNAMIC_CURRENT_ENV
  6. })
  7. const serverless = require('serverless-http');
  8. const requestHandler = (req, res) => { //
  9. const requrl = url.parse(req.url, true);
  10. const filename = "." + requrl.pathname; //这里的.表示的是相对路径
  11. fs.readFile(filename, function(err, data) {
  12. if (err) {
  13. res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
  14. return res.end("404 页面没有找到");
  15. }
  16. res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  17. res.write(data);
  18. console.log(`请求链接是:${req.url},请求方法是:${req.method}`);
  19. return res.end();
  20. });
  21. }
  22. exports.main = serverless(requestHandler);

The terminal enters the cloud function directory server folder, installs the npm install and then rolls back to the project root using the CLoudbase Cli command to deploy the cloud function to the cloud and create a route for the server cloud function cloud access, and then access the cloud access link using the browser or cURL command:

  1. cloudbase functions:deploy server
  2. cloudbase service:create -p /server -f server

This way we can access the resources inside the managed server through the link of cloud access, as long as the resources in the cloud function directory can be accessed, the cloud function "innate" into a server. Compare the difference between an integration request returning html and hosting Nodejs Server.

  1. https://xly-xrlur.service.tcloudbase.com/server/assets/index.html

Third, hosting Koa .js

Both Koa and Express are web application development frameworks based on the Nodejs platform that encapsulate HTTP Request objects and HTTP Response objects, as well as lifecycle maintenance, routing, view processing, and more. Cloud access and cloud functions can host Nodejs Server, which also supports hosting Koa and Express, as in the case of Koa.

1, hosting Koa

Let's also take the server cloud function as an example, first adding the koa dependency in the stack.json of the server cloud function, and then changing the index .js to the following code, still reading the index.html file in the acets file in the cloud function directory:

  1. const cloud = require('wx-server-sdk')
  2. const fs = require('fs')
  3. cloud.init({
  4. env: cloud.DYNAMIC_CURRENT_ENV
  5. })
  6. const serverless = require('serverless-http');
  7. const Koa = require('koa');
  8. const app = new Koa();
  9. app.use(async ctx => {//ctx是由koa传入的封装了request和response的变量,通过它可以访问request和response
  10. ctx.response.type = 'text/html;charset=utf-8'; //ctx.response就是Node的response对象
  11. ctx.response.body = fs.createReadStream('./assets/index.html');
  12. })
  13. exports.main = serverless(app);

After entering the cloud function directory to download the dependency of the cloud function, fall back to the project root to deploy the upload server cloud function, and then use the browser to open the server cloud function's cloud access address to see the parsed index .html.

Koa's Context context encapsulates node's request and response objects into a single object, providing many useful ways to write Web applications and APIs. A ccessors and methods in many contexts are delegated directly to their ctx.request or ctx.response for convenience. ctx.response is Node's response object, ctx.request is Node's request object.

2, Koa native routes

Using Koa also allows cloud functions and cloud access to be used as a file server, returning files from the cloud function directory to the browser, and we modify the code for the server cloud function to look like the previous managed Nodejs Server:

  1. const cloud = require('wx-server-sdk')
  2. const fs = require('fs')
  3. const url = require('url')
  4. cloud.init({
  5. env: cloud.DYNAMIC_CURRENT_ENV
  6. })
  7. const serverless = require('serverless-http');
  8. const Koa = require('koa');
  9. const app = new Koa();
  10. app.use( async ( ctx ) => {
  11. const requrl = url.parse(ctx.request.url, true);
  12. const filename = "." + requrl.pathname;
  13. ctx.response.type = 'text/html;charset=utf-8';
  14. ctx.body =fs.createReadStream(filename)
  15. })
  16. exports.main = serverless(app);

Upload the server cloud function deployment, and as before, we can enter the following address in the browser to access the index page in the asts folder in the server .html directory:

  1. https://xly-xrlur.service.tcloudbase.com/server/assets/index.html

Koa native routes take advantage of if... by parsing the url property of the request IncomingMessage. e lse to judge the path to return different results, but if there are too many routes, if... The larger the branch of else, the less conducive to code maintenance, the specific case is not much written here, the following directly with the Koa-router solution.

Four, Koa router middleware

Although we can rely on ctx.request.url, a more native way to handle routes manually, this will write a lot of processing code, which requires the corresponding routing middleware to control the route, with Koa-router recommended here, and koa-bodyparser middleware recommended. For the processing of POST requests, koa-bodyparser can parse ctx's formData data into ctx.request.body.

1. Use Koa router middleware

We'll still take the server cloud function as an example, add the following dependencies at package.json, and go to the server cloud function directory to download them:

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "serverless-http": "latest",
  4. "koa":"latest",
  5. "koa-bodyparser":"latest",
  6. "koa-router":"latest"
  7. }

Then modify the server cloud function to the following code, then deploy the upload server cloud function, and then access the address of the cloud access, note that the home page on the open page and about us can click, will jump to the route specified by koa-router, and return the appropriate content:

  1. const fs = require('fs')
  2. const cloud = require('wx-server-sdk')
  3. cloud.init({
  4. env: cloud.DYNAMIC_CURRENT_ENV
  5. })
  6. const serverless = require('serverless-http');
  7. const Koa = require('koa');
  8. const bodyParser = require('koa-bodyparser')
  9. const app = new Koa();
  10. const Router = require('koa-router')
  11. const router = new Router()
  12. app.use(bodyParser())
  13. router.get('/',async (ctx) => {
  14. //注意这里的路径哈,server为云接入的路由,在前面我们把server云函数的路由设置为server
  15. let html = `
  16. <ul>
  17. <li><a href="/server/home">首页</a></li>
  18. <li><a href="/server/about">关于我们</a></li>
  19. </ul>
  20. ctx.body = html
  21. })
  22. router.get('/home',async (ctx) => {
  23. ctx.response.type = 'text/html;charset=utf-8';
  24. ctx.response.body = fs.createReadStream('./assets/index.html');
  25. })
  26. router.get('/about', async ( ctx )=>{
  27. ctx.body = '欢迎您的关注,网页还在建设当中'
  28. })
  29. app.use(router.routes()) // 添加路由中间件
  30. app.use(router.allowedMethods()) // 对请求进行一些限制处理
  31. exports.main = serverless(app);

When we 云接入地址/home we return the index.html page in the asats folder under the cloud function directory, when in fact the cloud function directory does not have home this folder, the previous way to open the cloud access address 云接入地址/assets/index.html can not open, this is route redirection.

This case simply uses the GET method for registered routing, and we can also use POST, DELETE, PUT, DEL, ALL, and so on. And the koa-router route also supports variables and so on, so it doesn't unfold here.

2, routing middleware and cloud development

With routing middleware, we can integrate the most common GET and POST requests into a cloud function, such as database, cloud storage addition and deletion, so that the cloud function as an API server, forward back to the required data and perform specified operations. On the small terminal we can use the wx.request() interface to initiate HTTPS network requests (it is worth noting that the small terminal needs to add the domain name of cloud access to the whitelist of domain names in the small program), and on the Web side we can use axios.

Get the data in the database

For example, with Koa router, we can add a route getData to return the data results queried by the cloud database:

  1. router.get('/getData',async (ctx) => {
  2. ctx.body = await db.collection('china').where({
  3. gdp: _.gt(3000)
  4. })
  5. .field({
  6. _id:false,
  7. city: true,
  8. province: true,
  9. gdp:true
  10. })
  11. .orderBy('gdp', 'desc')
  12. .skip(0)
  13. .limit(10)
  14. .get()
  15. })

Get the return data on the small terminal:

  1. wx.request({
  2. url: 'https://xly-xrlur.service.tcloudbase.com/server/getData',
  3. success (res) {
  4. console.log(res.data.data)
  5. }
  6. })

Get the return data on the web side:

  1. const url ="https://xly-xrlur.service.tcloudbase.com/server/getData"
  2. axios.get(url).then(res => {
  3. console.log(res.data)
  4. }).catch(err => {
  5. console.log(err)
  6. })

Add a database to the database

We can also use Koa router to provide a POST interface to process parameters and data coming from the front end, for example, we can add data to the database, just pay attention to how Koa gets the parameters and data.

  1. router.post('/addData',async (ctx) => {
  2. const {userInfo} = await ctx.request.body
  3. const addUser = await db.collection('china').add({
  4. data:userInfo
  5. })
  6. ctx.body = addUser
  7. })

The code for the small terminal to initiate a POST request is as follows:

  1. wx.request({
  2. url: 'https://xly-xrlur.service.tcloudbase.com/server/addData',
  3. method:"POST",
  4. data:{
  5. userInfo:{
  6. Name: '腾讯云云开发',
  7. enName: 'CloudBase'
  8. }
  9. },
  10. success (res) {
  11. console.log(res)
  12. }
  13. })

The code that initiated the POST request on the web side is as follows:

  1. async function addData(){
  2. axios.post('https://xly-xrlur.service.tcloudbase.com/server/addData', {
  3. userInfo:{
  4. Name: '腾讯云云开发',
  5. enName: 'CloudBase'
  6. }
  7. })
  8. .then(function (response) {
  9. console.log(response);
  10. })
  11. .catch(function (error) {
  12. console.log(error);
  13. });
  14. }

We can also call the server cloud function on the small terminal or the Web side to see how the returned data objects are different from the past. Take a look at the difference between background functions and HTTP functions.