NodeJS③(http module)

what is http module

The http module is an official module provided by Node.js to create a web server. Through the http.createServer() method provided by the http module, an ordinary computer can be easily turned into a Web server, thereby providing external Web resource services.

In the network node, the computer responsible for consuming resources is called the client, and the computer
responsible for providing network resources to the outside world is called the server

If you want to use the http module to create a web server, you need to import it first:

const http = require('http');

The role of the http module

The difference between a server and an ordinary computer is that web server software, such as IIS, Apache, etc., is installed on the server. By installing these server software, an ordinary computer can be turned into a web server.

IIS is often used in asp.net development
Apache is often used in php development

In Node.js, we do not need to use third-party web server software such as IIS, Apache, etc. Because we can easily write a server software based on the http module provided by Node.js, through a few lines of simple code, to provide web services to the outside world.

Server related concepts

IP address

IP 地址It is the unique address of every computer on the Internet, so the IP address is unique. If "personal computer" is compared to "a phone", then "IP address" is equivalent to "telephone number", and data communication with the corresponding computer can only be performed on the premise of knowing the IP address of the other party.

Format of IP address: usually expressed in "dotted decimal" in the form of (abcd), where a, b, c, d are all decimal integers between 0 and 255. Example: IP address in dotted decimal (192.168.1.1)

Notice:

  • Every web server in the Internet has its own IP address, for example: You can run the ping www.baidu.com command in the Windows terminal to view the IP address of the Baidu server.
  • During development, your computer is both a server and a client. In order to facilitate testing, you can enter the IP address of 127.0.0.1 in your browser to access your computer as a server.

Domain names and nameservers

Although IP addresses can uniquely mark computers on the network, IP addresses are long strings of numbers, which are not intuitive and difficult to remember, so people have invented another set of character-based addressing schemes, the so-called address scheme 域名(Domain Name)地址.

There is a one-to-one correspondence between IP addresses and domain names, and this correspondence is stored in a computer called 域名服务器(DNS,Domain name server)a computer. The user only needs to access the corresponding server through the easy-to-remember domain name, and the corresponding conversion work is realized by the domain name server. Therefore, a domain name server is a server that provides translation services between IP addresses and domain names.

Notice:

  • Computers on the Internet can also work just fine with just an IP address. But with the blessing of domain names, the world of the Internet can become more convenient.
  • During development and testing, the domain name corresponding to 127.0.0.1 is localhost, and they all represent our own computer, and there is no difference in the use effect.

The port number

The port number in the computer is like the house number in real life. Through the house number, the takeaway brother can accurately deliver the takeaway to you in many rooms in the whole building.

In the same way, in a computer, you can run hundreds of web services. Each web service corresponds to a unique port number. The network request sent by the client can be accurately handed over to the corresponding web service for processing through the port number.

insert image description here
Notice:

  • Each port number cannot be used by multiple web services at the same time.
  • In practice, port 80 in the URL can be omitted.

Port 80 is open for HTTP (HyperText Transport Protocol), which is the most frequently used protocol for surfing the Internet, mainly used for WWW (World Wide Web), the protocol for transmitting information on the World Wide Web.

Create the most basic web server

create process

Basic steps to create a web server:

  • import http module
  • Create a web server instance
  • Bind the request event to the server instance and listen to the client's request
  • start the server

Note: The server you create in this way can only be accessed by yourself, not by others. You might be asking what's the use of this.
Because in the development stage, both the server side and the browser side are developed on the same computer. The http module can quickly meet our development requirements.

①Import the http module
If you want to create a web server on your computer to provide web services to the outside world, you need to import the http module: ②Create
insert image description here
a web server instance
Call the http.createServer() method to quickly create a web server instance:
insert image description here

③Bind the request event
to the server instance Bind the request event to the server instance to monitor the network requests sent by the client: ④Start the
insert image description here
server
Call the .listen() method of the server instance to start the current web server instance:
insert image description here

Overall code implementation:

// 1. 导入 http 模块
const http = require('http')
// 2. 创建 web 服务器实例
const server = http.createServer()
// 3. 为服务器实例绑定 request 事件,监听客户端的请求
server.on('request', function (req, res) {
    
    
  console.log('Someone visit our web server.')
})
// 4. 启动服务器(让服务器监听8080端口)
server.listen(8080, function () {
    
      
  console.log('server running at http://127.0.0.1:8080')
})

req request object

As long as the server receives the client's request, it will call the request event handler bound for the server through server.on(). If you want to access data or properties related to the client in the event handler , you can use the following methods:
insert image description here

req.url is the URL address
requested by the client req.method is the method type requested by the client

E.g:

const http = require('http')
const server = http.createServer()
// req 是请求对象,包含了与客户端相关的数据和属性
server.on('request', (req) => {
    
    
  // req.url 是客户端请求的 URL 地址
  const url = req.url
  // req.method 是客户端请求的 method 类型
  const method = req.method
  const str = `Your request url is ${
      
      url}, and request method is ${
      
      method}`
  console.log(str)
})
server.listen(80, () => {
    
    
  console.log('server running at http://127.0.0.1')
})

In the above code, we only process the content of the request in the server and do not respond, so the client cannot get the returned data.

res response object

In the server's request event handler, if you want to access server-related data or properties , you can use the following methods:
insert image description here
For example:

const http = require('http')
const server = http.createServer()
// req 是请求对象,包含了与客户端相关的数据和属性
server.on('request', (req, res) => {
    
    
  // req.url 是客户端请求的 URL 地址
  const url = req.url
  // req.method 是客户端请求的 method 类型
  const method = req.method
  const str = `Your request url is ${
      
      url}, and request method is ${
      
      method}`
  console.log(str)
  // 调用 res.end() 方法,向客户端响应一些内容
  res.end(str)
})
server.listen(80, () => {
    
    
  console.log('server running at http://127.0.0.1')
})

insert image description here

Solve the problem of Chinese garbled characters

When the res.end() method is called to send Chinese content to the client, there will be a problem of garbled characters. At this time, the encoding format of the content needs to be manually set:

res.setHeader('Content-Type', 'text/html; charset=utf-8')

Call the res.setHeader() method to set the Content-Type response header to solve the problem of Chinese garbled characters.
For example:

const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
    
    
  // 定义一个字符串,包含中文的内容
  const str = `您请求的 URL 地址是 ${
      
      req.url},请求的 method 类型为 ${
      
      req.method}`
  // 调用 res.setHeader() 方法,设置 Content-Type 响应头,解决中文乱码的问题
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  // res.end() 将内容响应给客户端
  res.end(str)
})

server.listen(80, () => {
    
    
  console.log('server running at http://127.0.0.1')
})

Remember to restart the server to take effect after each modification of the server-side code.

Respond to different html content according to different urls

Method: Get the request address of the client, and then make a targeted response.

For example: we respond differently to a website's home page and related pages

Implementation steps:
① Get the url address of the request
② Set the default response content to 404 Not found
③ Determine whether the user requested is / or /index.html home page
④ Determine whether the user requested is /about.html About page
⑤ Set Content- Type response header to prevent Chinese garbled
⑥ Use res.end() to respond to the client

Code:

const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
    
    
  // 1. 获取请求的 url 地址
  const url = req.url
  // 2. 设置默认的响应内容为 404 Not found
  let content = '<h1>404 Not found!</h1>'
  // 3. 判断用户请求的是否为 / 或 /index.html 首页
  // 4. 判断用户请求的是否为 /about.html 关于页面
  if (url === '/' || url === '/index.html') {
    
    
    content = '<h1>首页</h1>'
  } else if (url === '/about') {
    
    
    content = '<h1>关于页面</h1>'
  }
  // 5. 设置 Content-Type 响应头,防止中文乱码
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  // 6. 使用 res.end() 把内容响应给客户端
  res.end(content)
})

server.listen(80, () => {
    
    
  console.log('server running at http://127.0.0.1')
})

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/124272920