current position:Home>node. JS server

node. JS server

2022-04-29 16:34:01Bear look at the camera

The article may be a little boring, but it's all about dry goods

How to explain the server

  • A server is a machine that provides network services , By installing special software ( Or run a special piece of code ) To provide services .
  • The server = The computer + Can you give it to other computers / Software provided by the device
  • Client and server : The service is provided by the server It is the client that enjoys the service

Server type

  • Different services Different types of servers
  • web The server . install apache, tomcat, iis, Or in nodejs Environment write code To provide : Picture view , News browsing .... And so on .
  • ftp The server . install serv-U Software , Provide file downloads for other computers , Shared services .
  • database server . install mysql Software , Provide database services for other computers
  • Browser side and web The server is through http( Or is it https) agreement To request and respond


ip Address
  • Full name :Internet Protocol Address
  • effect : Identify a network device ( Computer 、 mobile phone 、 TV ) stay A specific network The address in . To access resources on a computer , First find its ip
domain name
  • One IP The port of the address can have 65536 individual , Range is from [0,65535]). Different ports are occupied by different software , To provide different services
  • Multiple servers can be used to install software , such as Web service 、FTP service 、SMTP Service etc. . obviously , Just passed ip Addresses cannot distinguish between different services
  1. To provide services, the server must pass Specified port
  2. Both the server and the client need to communicate through the port
  3. Ports are programmable
  4. Some port numbers are reserved


  • Make communication rules between client and server . Different agreements work differently .

  • HTTP(HyperText Transfer Protocol) Hypertext transfer protocol .

  • The parties to the agreement : Browser and web The server

  • The request is initiated by the browser

  • HTTP There is a clear stipulation in the agreement that Request data and The response data The format of ( message )

  • browser request resources Observe http agreement :   Request message ( Request line , Request header , Request body )

  • The server return resources Observe http agreement :   response message ( Response line , Response head , Response body )


use http Module write a simple server


  1. First introduce http modular
  2. Create a server
  3. Start the server
// 1.  introduce http modular 
const http = require('http');

// 2.  Create services 
const server = http.createServer(function(req, res) {
  console.log(' Someone came to visit ')
  //  Send content to clients , And end this response 
  res.end('hello world');
// 3.  Start the service 
server.listen(8081, function() {
  console.log(' Server started successfully , Please be there. http://localhost:8081 Medium visit ....');
 Copy code 

Be careful :

  • Don't close the small black window , It's the server
  • The server itself will not take the initiative ( The little black window doesn't look any different ), It is always waiting for the client to access
  • Don't use the mouse to select the contents of the small black window , Will cause the program to fake death
  • After modifying the code, restart
  • change res.end() The content of , restart after , Observe again .
  • Restart the service : Is to run the program again ( Press the up arrow , Enter again )

How to understand responses and requests


When web When the server is ready , If there is no client to access it , It won't have any effect . That is, the callback function will not execute . And every request , Will cause the callback function to execute once .

Respond to

adopt res.end To set the content of the response ,res.end() The format can only be buffer Or is it String


  • Introduce core modules , Got http It's an object .
  • http.createServer Method to create a http service . Parameter is a callback function : When there is http When asked to come in , It will be called automatically . Ask for once , It is called once .
  •  The first parameter :` Client requests `.
     The second parameter :` Set the response to this request `.
     Copy code 
  • **res.end()** : Set the response body , End request .
     Copy code 
  • server.listen() Used to monitor ports .
  • Format :server.listen( Port number ,[ Callback function ]) . Callbacks are optional .

  • explain :

  • If the monitoring is successful , The callback function will execute once .

  • If it doesn't work ( For example, the port is occupied ), Will report a mistake

content type effect

  • content-type It is used to tell the other party the type of data transmitted this time
  • Set... In the request header content-type To tell the server , What type of data does this request carry
  • Set... In the response header content-type To tell the server , What type of data is returned this time


html:`res.setHeader('content-type', 'text/html;charset=utf8')`
css:`res.setHeader('content-type', 'text/css;charset=utf8')`
js:`res.setHeader('content-type', 'application/javascript')`
png:`res.setHeader('content-type', 'image/png')`
json data :`res.setHeader('content-type', 'application/json;charset=utf-8')`
 Copy code 


res.setHeader('content-type', value )

Set up statusCode

effect : Set up http Protocol request status code

res.statusCode = 301;
// res.setHeader('location','')
res.statusCode = 404
res.statusCode = 500
 Copy code 

a key express

  • expresss It's a third-party module ( stay npm Can be downloaded from ), Download it before using it , Create the project before downloading the package , And pass npm init establish package.json file
  • Create a new folder , Suppose the name is learn-express( The directory name should not have Chinese characters , And don't want the name of a bag ), Run in this directory npm init -y Command to generate package.json file
// 0.  load  Express
const express = require('express')

// 1.  call  express()  Get one  app
//     Be similar to  http.createServer()
const app = express()

// 2.  Set the processing function corresponding to the request 
//     When the client uses  GET  Method request  /  The second parameter will be called when : Request handling function 
app.get('/', (req, res) => {
  res.send('hello world')

// 3.  Monitor port number , start-up  Web  service 
app.listen(3000, () => console.log('app listening on port 3000!'))
 Copy code 

copyright notice
author[Bear look at the camera],Please bring the original link to reprint, thank you.

Random recommended