Implement an HTTP server program (file server) with Node.js

http

The purpose of Node.js development is to write web server programs in JavaScript. Because JavaScript has actually ruled browser-side scripting, its advantage is that it has the largest number of front-end developers in the world. If you have mastered JavaScript front-end development, and then learn how to apply JavaScript in back-end development, it is a veritable full-stack.

HTTP protocol

To understand the working principle of the Web server program, first of all, we need to have a basic understanding of the HTTP protocol. If you are not familiar with the HTTP protocol, first take a look at the introduction to the HTTP protocol.

HTTP server

To develop an HTTP server program, it is unrealistic to handle TCP connections and parse HTTP from scratch. These tasks have actually been completed by the http module that comes with Node.js. The application program does not directly deal with the HTTP protocol, but operates the request and response objects provided by the http module.

The request object encapsulates the HTTP request, and we can get all the HTTP request information by calling the properties and methods of the request object;

The response object encapsulates the HTTP response, and we can return the HTTP response to the browser by operating the method of the response object.

Implementing an HTTP server program with Node.js is very simple. Let's implement the simplest web program hello.js, which returns Hello world! for all requests:

'use strict';

// 导入http模块:
var http = require('http');

// 创建http server,并传入回调函数:
var server = http.createServer(function (request, response) {
    // 回调函数接收request和respons

Guess you like

Origin blog.csdn.net/2301_76484015/article/details/129701838