Nodejs quickly builds a simple HTTP server and publishes remote access to the public network

Article directory

  • Preface
  • 1. Install Node.js environment
  • 2. Create node.js service
  • 3. Access node.js service
  • 4.Intranet penetration
    • 4.1 Install and configure cpolar intranet penetration
    • 4.2 Create tunnel mapping local port
  • 5. Fixed public network address

Before I start the text, I would like to recommend a website to you. A few days ago, I discovered a giant artificial intelligence learning website. It is easy to understand and humorous. I can’t help but share it with everyone. Click to jump to the website.

Foreword

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 a project of the Linux Foundation. Node.js uses the V8 runtime code developed by Google and uses technologies such as event-driven, non-blocking and asynchronous input and output models to improve performance and optimize application transfer volume and scale. 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 a js file and a html file, which need to be placed in the same directory, and then Open using vscode.

  • game.html file
  • nodetest.js file

image-20230302155043387

Add the following html code in game.html and save it. The following code is an html page mini-game (Snake)

<!DOCTYPE html>
<html>
<head>
<title>Snake</title>
<meta charset="UTF-8">
<meta name="keywords" content="Snake">
<meta name="Description" content="This is a small game for beginners to learn">
<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">
\t
</canvas>
</div>
 
<script type="text/javascript">
 //Get drawing tools
/*
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");//Get the context
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 =[];//Define a snake and draw its body
    var snakeCount = 6;//Initialize the length of the snake
var foodx =0;
var foody =0;
    var togo =0;
    function drawtable()//Function to draw a map
    {<!-- -->
 
 
    for(var i=0;i<60;i + + )//Draw a vertical line
    {<!-- -->
    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 + + )//Draw a horizontal line
    {<!-- -->
    ctx.strokeStyle="black";
    ctx.beginPath();
    ctx.moveTo(0,15*j);
    ctx.lineTo(900,15*j);
    ctx.closePath();
    ctx.stroke();
    }
    \t
    for(var k=0;k<snakeCount;k + + )//Draw the body of the snake
{<!-- -->
ctx.fillStyle="#000";
if (k==snakeCount-1)
{<!-- -->
ctx.fillStyle="red";//The color of the snake head is distinguished from the body
}
ctx.fillRect(snake[k].x,snake[k].y,15,15);//The first two numbers are the starting coordinates of the rectangle, and the last two numbers are the length and width of the rectangle.
\t\t\t
}
//draw food
    ctx.fillStyle ="black";
ctx.fillRect(foodx,foody,15,15);
ctx.fill();
    \t
    }
 
    
    function start()//Define the coordinates of the snake
    {<!-- -->
    //var snake =[];//Define a snake and draw its body
        //var snakeCount = 6;//Initialize the length of the snake
\t\t
for(var k=0;k<snakeCount;k + + )
    {<!-- -->
    snake[k]={<!-- -->x:k*15,y:0};
    \t\t\t
            }
\t\t\t
drawtable();
          addfood();//Call the add food function in start
 
    }
 
    function addfood()
{<!-- -->
foodx = Math.floor(Math.random()*60)*15; //Randomly generate a number between 0-1
foody = Math.floor(Math.random()*40)*15;
\t\t
for (var k=0;k<snake;k + + )
{<!-- -->
if (foodx==snake[k].x & amp; & amp;foody==sanke[k].y)//Prevent the generated random food from falling on the snake
{<!-- -->
addfood();
}
}
\t
\t
}
    \t\t
   function move()
   {<!-- -->
switch (togo)
{<!-- -->
case 1: snake.push({<!-- -->x:snake[snakeCount-1].x-15,y:snake[snakeCount-1].y}); break;//Go left
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();//Delete the first element of the array
   ctx.clearRect(0,0,900,600);//Clear the canvas and redraw it
   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()//The length increases by 1 after eating food
   {<!-- -->
    if(snake[snakeCount-1].x==foodx & amp; & amp;snake[snakeCount-1].y==foody)
   {<!-- -->
addfood();
snakeCount + + ;
snake.unshift({<!-- -->x:-15,y:-15});
   }
   
   }
   //death function
   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()//Call function
{<!-- -->
start();
setInterval(move,150);
drawtable();
\t
\t
 
}
</script>
</body>
</html>

Add the following js code to the nodetest.js file. The following code means to open an http service and set up the listening port 3000 Number

const http = require('http');

//Load file module
const fs = require("fs");


const hostname = '127.0.0.1';
//port
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 .\\
odetest.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 public IP, 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 Create

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.js service 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 name

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 Update

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.