A quick way to build a simple Node.js HTTP server and publish remote access to the public network

Preface

Node.js is an open source, cross-platform runtime environment for running JavaScript on the server side. Node.js is owned and maintained by the OpenJS Foundation (formerly the Node.js Foundation, which merged with the JS Foundation) and is also a project of the Linux Foundation. Node.js uses the V8 running code developed by Google and uses technologies such as event-driven, non-blocking and asynchronous input and output models to improve performance and optimize the transmission volume and scale of applications. These techniques are typically used in data-intensive real-time applications.

Most of the basic modules of Node.js are written in JavaScript language. Before the emergence of Node.js, JavaScript was usually used as a client-side programming language, and programs written in JavaScript often ran on the user's browser. The emergence of Node.js enables JavaScript to be used for server-side programming. Node.js contains a series of built-in modules that allow the program to be separated from Apache HTTP Server or IIS and run as an independent server. The following will introduce how to access the windwos node.js server under a remote public network in a few simple steps.

1. Install Node.js environment

Download node.js from the official website, we choose 64-bit one-click installation

https://nodejs.org/zh-cn/download/

image-20230302141011787

After installation, we open cmd, enter the command and the version number will appear normally, indicating that the installation is successful. The one-click installation version will configure the environment variables by default.

node -v

image-20230302150424377

2. Create node.js service

Here we create a simple nodejs service locally and create a snake page game for demonstration.

First create a folder locally, and create 2 new files in the folder, one is jsa file and the other is a htmlfile. They need to be placed in the same directory, and then open with vscode.

  • game.html文件
  • nodetest.js文件

image-20230302155043387

Add game.htmlthe following htmlcode and save it. The following code is an html page game (Snake)

<!DOCTYPE html>
<html>
<head>
	<title>贪吃蛇</title>
	<meta charset="UTF-8">
	<meta name="keywords" content="贪吃蛇">
	<meta name="Description" content="这是一个初学者用来学习的小游戏">
	<style type="text/css">
	*{
      
      margin:0;}
	.map{
      
      margin:100px auto;
		height:600px;
		width:900px;
		background:#00D0FF;
		border:10px solid #AFAEB2;
		border-radius:8px;
	}
	</style>
</head>
 
<body>
<div class="map">
<canvas id="canvas" height="600" width="900">
	
</canvas>
</div>
 
<script type="text/javascript">
 //获取绘制工具
	/*
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d");//获取上下文
	ctx.moveTo(0,0);
	ctx.lineTo(450,450);*/
	var c=document.getElementById("canvas");
    var ctx=c.getContext("2d");
    /*ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.lineTo(450,450);
    ctx.stroke();
    */
 
    var snake =[];//定义一条蛇,画蛇的身体
    var snakeCount = 6;//初始化蛇的长度
	var foodx =0;
	var foody =0;
    var togo =0;
    function drawtable()//画地图的函数
    {
      
      
 
 
    	for(var i=0;i<60;i++)//画竖线
    	{
      
      
    		ctx.strokeStyle="black";
    		ctx.beginPath();
    		ctx.moveTo(15*i,0);
    		ctx.lineTo(15*i,600);
    		ctx.closePath();
    		ctx.stroke();
    	}
        for(var j=0;j<40;j++)//画横线
    	{
      
      
    		ctx.strokeStyle="black";
    		ctx.beginPath();
    		ctx.moveTo(0,15*j);
    		ctx.lineTo(900,15*j);
    		ctx.closePath();
    		ctx.stroke();
    	}
    	
    	for(var k=0;k<snakeCount;k++)//画蛇的身体
			{
      
      
			ctx.fillStyle="#000";
			if (k==snakeCount-1)
			{
      
      
				ctx.fillStyle="red";//蛇头的颜色与身体区分开
			}
			ctx.fillRect(snake[k].x,snake[k].y,15,15);//前两个数是矩形的起始坐标,后两个数是矩形的长宽。
			
			}
			//绘制食物	
    		ctx.fillStyle ="black";
	     ctx.fillRect(foodx,foody,15,15);
	     ctx.fill();
    	
    }
 
    
    function start()//定义蛇的坐标
    {
      
      
    	//var snake =[];//定义一条蛇,画蛇的身体
        //var snakeCount = 6;//初始化蛇的长度
		
		for(var k=0;k<snakeCount;k++)
    		{
      
      
    			snake[k]={
      
      x:k*15,y:0};
    			
            }
			
		  drawtable();
          addfood();//在start中调用添加食物函数
 
    }
 
    function addfood()
	{
      
      
	foodx = Math.floor(Math.random()*60)*15; //随机产生一个0-1之间的数
	foody = Math.floor(Math.random()*40)*15;
		
		for (var k=0;k<snake;k++)
		{
      
      
			if (foodx==snake[k].x&&foody==sanke[k].y)//防止产生的随机食物落在蛇身上
			{
      
      	
			addfood();
			}
		}
	
	
	}	
    		
   function move()
   {
      
      
	switch (togo)
	{
      
      
	case 1: snake.push({
      
      x:snake[snakeCount-1].x-15,y:snake[snakeCount-1].y}); break;//向左走
	case 2: snake.push({
      
      x:snake[snakeCount-1].x,y:snake[snakeCount-1].y-15}); break;
	case 3: snake.push({
      
      x:snake[snakeCount-1].x+15,y:snake[snakeCount-1].y}); break;
	case 4: snake.push({
      
      x:snake[snakeCount-1].x,y:snake[snakeCount-1].y+15}); break;
	case 5: snake.push({
      
      x:snake[snakeCount-1].x-15,y:snake[snakeCount-1].y-15}); break;
	case 6: snake.push({
      
      x:snake[snakeCount-1].x+15,y:snake[snakeCount-1].y+15}); break;
	default: snake.push({
      
      x:snake[snakeCount-1].x+15,y:snake[snakeCount-1].y});
	}
    snake.shift();//删除数组第一个元素
   	ctx.clearRect(0,0,900,600);//清除画布重新绘制
   	isEat();
	isDead();
	drawtable();
   } 			
   
   function keydown(e)
   {
      
      
   switch(e.keyCode)
		{
      
      
         case 37: togo=1; break;
		 case 38: togo=2; break;
		 case 39: togo=3; break;
		 case 40: togo=4; break;
		 case 65: togo=5; break;
		 case 68: togo=6; break;
		}
   }
   
   function isEat()//吃到食物后长度加1
   {
      
      
    if(snake[snakeCount-1].x==foodx&&snake[snakeCount-1].y==foody)
   {
      
      
		addfood();
		snakeCount++;
		snake.unshift({
      
      x:-15,y:-15});
   }
   
   }
   //死亡函数
   function isDead()
   {
      
      
    if (snake[snakeCount-1].x>885||snake[snakeCount-1].y>585||snake[snakeCount-1].x<0||snake[snakeCount-1].y<0)
		{
      
      
        

		window.location.reload();
		}
   }
   
    document.onkeydown=function(e)
{
      
      
	keydown(e);
 
} 
window.onload = function()//调用函数
{
      
       
	start();
	setInterval(move,150);
	drawtable();
	
	
 
}
</script>
</body>
</html>

nodetest.jsAdd the following jscode to the file. The following code means to open one http服务and set the listening 3000port number.

const http = require('http');

//加载文件模块
const fs = require("fs");


const hostname = '127.0.0.1';
//端口
const port = 3000;

const server = http.createServer((req, res) => {
    
    
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  
  fs.readFile('./game.html', (err, data) => {
    
    
    if (err) throw err;
    console.log(data.toString);
    res.end(data);
  });
  
  
 
});

server.listen(port, hostname, () => {
    
    
  console.log(`Server running at http://${
      
      hostname}:${
      
      port}/`);
});

3. Access node.js service

After we write the relevant code, we start the service. Enter the command in the vscode console [note that you need to enter the corresponding file directory to execute the command]

node .\nodetest.js

image-20230302170633966

There is a normal return prompt service under the local port 3000. We open the browser and visit http://127.0.0.1:3000/. The snake interface appears to indicate success [Game control: keyboard up, down, left and right keys]

image-20230302171105342

4.Intranet penetration

Here we use cpolar for intranet penetration, which supports http/https/tcp protocols, does not limit traffic, does not require a public IP address, and does not require setting up a router. It is simple to use.

4.1 Install and configure cpolar intranet penetration

cpolar official website: https://www.cpolar.com/

Visit the cpolar official website, register an account, and then download and install the client. For specific installation instructions, please refer to the official website documentation tutorial.

  • Windows system: After downloading the installation package from the official website, double-click the installation package and install it by default.
  • Linux system: supports one-click automatic installation script. For details, please refer to the official website documentation - Getting Started Guide

20230130105715

4.2 Create tunnel mapping local port

After cpolar is successfully installed, access the local 9200 port http://localhost:9200 on the browser and log in using the cpolar email account.

20230130105810

Click Tunnel Management - Create Tunnel on the left dashboard to create an http tunnel pointing to the local port 3000.

  • Tunnel name: You can customize the name. Be careful not to duplicate the existing tunnel name.
  • Protocol: Select http
  • Local address: 3000
  • Domain name type: Choose a random domain name for free
  • Region: Select China vip

Click创建

image-20230302171633772

After the tunnel is successfully created, click Status on the left - Online Tunnel List, view the generated public network address, and then copy the address

image-20230302171740715

Open the browser and use the public address above to access. At this point, we have successfully published the local node.jsservice to the public address.

image-20230302171817498

5. Fixed public network address

Since the tunnel created using cpolar above uses a random public network address, it will change randomly within 24 hours, which is not conducive to long-term remote access. Therefore, we can configure a second-level subdomain name for it. This address is a fixed address and will not change randomly.

  • Reserve a second-level subdomain

Log in to the cpolar official website, click Reserve on the left, select to reserve the second-level subdomain name, set a second-level subdomain name, click Reserve, and copy the reserved second-level subdomain name after the reservation is successful.

image-20230302172317079

After the reservation is successful, copy the reserved second-level subdomain name address

image-20230302172454064

  • Configure second-level subdomain names

Visit http://127.0.0.1:9200/, log in to the cpolar web UI management interface, click Tunnel Management - Tunnel List on the left dashboard, find the 3000 tunnels you want to configure, and click Edit on the right

image-20230302172856768

Modify the tunnel information and configure the successfully reserved second-level subdomain name into the tunnel.

  • Domain name type: Select a second-level subdomain name
  • Sub Domain: Fill in the successfully reserved second-level subdomain name

Click更新

image-20230302172806823

After the update is completed, open the online tunnel list. At this time, you can see that the public network address has changed and the address name has become the reserved second-level subdomain name. Copy it.

image-20230302172935943

Then use the fixed http address to open the browser access

image-20230302173012863
The access is successful. Now the public network address is fixed and will not change randomly. Successfully penetrated the cpolar intranet to achieve remote access to nodejs services without requiring a public IP address or setting up a router.

Reprinted from cpolar pole cloud article: Remote access to Node.js service on public network [cpolar intranet penetration]

Guess you like

Origin blog.csdn.net/m0_67768006/article/details/132547968