[Server] Use Nodejs to build an HTTP web server

5a2585dded9b416fb4ea58637b42ed39.png

  Yan-yingjie's homepage

Awareness of the past, not remonstrance, knowing the future, can be pursued  

C++ programmer, 2024 electronic information graduate student


Table of contents

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


@[TOC]

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 that can run JavaScript on the server side. Node.js is owned and maintained by the OpenJS Foundation (formerly the Node.js Foundation, which has been merged with the JS Foundation), and is also a project of the Linux Foundation. Node.js uses V8 developed by Google to run the code, using technologies such as event-driven, non-blocking and asynchronous input and output models to improve performance, and 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 appearance of Node.js, JavaScript was usually 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 be separated from Apache HTTP Server or IIS, and run as an independent server. 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 the Node.js environment

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

Download | Node.js

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 a 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 jsa file and one htmlfile, which need to be placed in the same directory, and then opened with vscode.

  • game.html文件

  • nodetest.js文件

image-20230302155043387

Add game.htmlthe following htmlcode and save it, the following code is a 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 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 .\nodetest.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: cpolar - a secure intranet penetration tool

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: supports one-click automatic installation scripts, please refer to the official website documentation for details - Getting Started Guide

20230130105715

4.2 Create a tunnel to map a 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创建

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.jsservice 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 a 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更新

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-20230302173012863The 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.

Guess you like

Origin blog.csdn.net/m0_73367097/article/details/130790051