[Nodejs] Use Nodejs to build HTTP services and realize remote access to the public network

Article directory

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

Reprinted from the article of Intranet Penetration Tool: Use Nodejs to build HTTP service and realize remote access to the public network “Intranet Penetration”

Foreword

Node.js is an open source, cross-platform runtime environment capable of running JavaScript on the server side. Node.js is owned and maintained by the OpenJS Foundation (formerly the Node.js Foundation, which was merged with the JS Foundation), and is a project of the Linux Foundation. Node.js uses V8 developed by Google to run the code, using techniques such as event-driven, non-blocking and asynchronous input and output models to improve performance, which can 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 advent of Node.js, JavaScript was often used as a client-side programming language, and programs written in JavaScript were often run on the user’s browser. The advent of Node.js enabled JavaScript to be used for server-side programming as well. Node.js contains a series of built-in modules, so that the program can run as an independent server without Apache HTTP Server or IIS. The following will introduce how to access the server of windwos node.js under the 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 the installation is complete, we open cmd, and the input command has a normal version number, indicating that the installation is successful. One-click installation version, the environment variable will be configured by default.

node -v

image-20230302150424377

2. Create node.js service

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

First create a folder locally, and create two new files in the folder, one is a js file and one html file, which need to be placed in the same directory, and then Open it with vscode.

  • game.html
  • nodetest.js file

image-20230302155043387

Add the following html code in game.html and save it. The following code is a html page game (snake)

<!DOCTYPE html>
<html>
<head>
<title>Eating Snake</title>
<meta charset="UTF-8">
<meta name="keywords" content="Snake 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 the drawing tool
/*
var canvas = document. getElementById("canvas");
var ctx = canvas.getContext("2d");//get 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, draw the snake's body
    var snakeCount = 6;//Initialize the length of the snake
var foodx = 0;
var foody = 0;
    var togo = 0;
    function drawtable()//The function of drawing the map
    {<!-- -->
 
 
    for(var i=0;i<60;i + + )//draw vertical lines
    {<!-- -->
    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 the 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, draw the snake's 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 function of adding food 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 (to go)
{<!-- -->
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
   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()//Add 1 to the length 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 a http service and set the listening port to 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 have written 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, 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 internal network penetration, supports http/https/tcp protocol, does not limit traffic, does not need public network IP, and does not need to set up routers, it is easy 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 tutorials, 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: support one-click automatic installation script, please refer to the official website document for details – getting started

20230130105715

4.2 Create a tunnel mapping local port

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

20230130105810

Click Tunnel Management on the left dashboard – Create Tunnel 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 on the status on the left – online tunnel list, view the generated public network address, and then copy the address

image-20230302171740715

Open the browser, we use the above public network address to access, so far, we have successfully published the local node.js service to the public network address

image-20230302171817498

5. Fixed public network address

Since the above tunnel created by using cpolar 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, which 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, choose 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 address

image-20230302172454064

  • Configure the second-level subdomain

Visit http://127.0.0.1:9200/, log in to the cpolar web UI management interface, click Tunnel Management on the left dashboard – Tunnel List, find the 3000 tunnel to be configured, 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 reserved sub-domain name

Click Update

image-20230302172806823

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

image-20230302172935943

Then use the fixed http address to open browser access

image-20230302173012863
The access is successful, and now the public network address is fixed and will not change randomly. Successfully penetrated through the cpolar intranet to achieve remote access to nodejs services, without the need for a public network IP or a router.