current position:Home>Talking about nodejs server

Talking about nodejs server

2022-04-29 18:45:02Joker_ Z

Server and client

  • The server : A machine that can provide network services , adopt Install special software To provide services
  • client : The service is provided by the server , It is the client that enjoys the service

The type of server

  • web The server : Be able to provide Internet services
  • ftp The server : Can provide file download 、 Shared services
  • database server : Be able to provide database services for other computers

web What can the server do

  • Enjoy... Through the browser web Services provided by the server
  • We usually use url Address to access a web Resources on the server
  • The browser initiates a request ,web After the server receives the request , In response to this request , And return the result to the browser
  • Browser and client are through http( perhaps https) Protocol for request and response

ip Address

1. effect : Identify the address of a network device in a specific network
2. classification :ipV4 and ipV6
3. Check your own computer ip Address : Open the command prompt window , Enter the command ipconfig, You can see Especially this machine ip Address

domain name

  • ip The alias of the address
  • localhost This domain name refers specifically to This address


  • One ip The port of the address can have 65536 individual
  • Different ports are occupied by different software , Provide different services
  • Server to provide services , The specified port must be provided
  • Both the server and the client communicate through ports
  • Ports are programmable


  • The parties to the agreement : Browser side and server side
  • The request is initiated by the browser side
  • HTTP There is a clear stipulation in the agreement that Request data and The response data The format of :
  • The browser requests resources to comply with http agreement : Request message ( Request line , Request header , Request body )
  • The resources returned by the server should comply with http agreement : response message ( Response line , Response head , Response body )

The process of client accessing server

1. The user enters the domain name
2.DNS analysis : Resolve the domain name to ip
3. Browser side press ip Address initiate request
4. Check the port on the server side
5. The server side found the service program
6. The server side processes the request and returns the response to the browser side

use nojs Core module http Write a simple web The server

// 1.  introduce http modular 
const http = require('http');

// 2.  Create services 
// Every time you receive a request , Callbacks are executed 
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 

The following is the result output on the page : image.png Be careful

  • Don't close the small black window , It's the server
  • The server itself will not take the initiative , 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


Understand requests and responses

request : When web When the server is ready , If there is no client to access it , It won't have any effect , The callback function does not execute , Every time a client initiates a request , The callback function will 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

Different browsers return different content

  • attribute :req.url() Get the resource address of the request after the port number
  • req.url Must be based on / At the beginning
  • In modern browsers , They will Automatically Go to the request server favicon.ico

content-type attribute

1. effect : stay http Agreement ,content-type It is used to tell the other party the type of data transmitted this time
2. Set... In the request header content-type To tell the server , What type of data does this request carry
3. Set... In the response header content-type To tell the browser , What type of data is returned this time

Several common file types and content-type attribute

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

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

Set up statusCode

  • effect : Namely http Response status code of
  • Format :res.statusCode = value

.html Secondary request in file

Get... From the server html After the document , If this html Other external resources are also referenced in the file ( picture , Style files, etc ), Then the browser will resend the request , This is the second request .

image.png The following is the output to the page image.png



  • Express It's based on Node.js platform , Fast 、 to open up 、 minimalist web Development framework .
  • We use... In front of us http Module to support web service , Now use express To write web service
  • about node.js Come on ,Express It's a third-party module , Have a lot of API Support , Powerful and flexible middleware characteristic
  • Express incorrect Node.js Second abstraction of existing features , Just expand on it Web Basic functions required by application

middleware The understanding of the :
It can provide better services for users
It can be easily disassembled

Run the first express Program

  1. Let's create an empty folder first , And initialize this folder item
  2. download express package
  3. Create a folder under the root of this folder .js file

Next steps :

// 1.  Introduce what we downloaded express package 
const express = require('express')

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

// 3.  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(8022, () => console.log(' Service started successfully '))
 Copy code 

Hosting static resources -web The server

  • Giving users direct access to static resources is a web The most basic function of the server
  • for example , Above url They are asking for a picture , A style file , One copy js Code . What we achieve web The server needs to be able to directly return the contents of these files to the client browser
  • Learn from the front http When the module , We have implemented these functions , But it takes a lot of code , Now use express frame , Just one sentence of code can do it , The code is  app.use(express.static('public'))
// 2.  Set the processing function corresponding to the request 
 Copy code 
  • here , All in public The content under can be accessed directly

Routing and interfaces

Format :

const app = express();

//  Define routes 
 Copy code 

Be careful :

  • app yes express example .(const app = express())
  • METHOD It's a HTTP Request method . All lowercase format . Such as :post,get,delete etc.
  • PATH It's the request path ( Equivalent to the http Used in the module url.parse(req.url).pathname

HANDLER It is the processing function to be executed when the route matches .(req,res)=>{ }

Browser's url And the path of the server

browser url Server path

copyright notice
author[Joker_ Z],Please bring the original link to reprint, thank you.

Random recommended