Nodejs creates a simple http service

  1. Introduce http module

    let http = require('http');
    
  2. Create service instance

    let server = http.createServer();
    
  3. Waiting for request

    server.on('request',(request,response) => {
          
          
        console.log('请求收到');
        let str = '';
        if (request.url == '/') {
          
          
            str = 'welcome to Home';
        } else {
          
          
            str = `welcome to ${
            
            request.url}`;
        }
        response.write(str);// 发送数据
        response.end();// 结束连接
             // 等价于
     	response.end(str);// 发送响应并结束响应(更常用)
    })
    
    1. When the client requests, it will automatically trigger the server's request request event, and then call the callback function

    2. The request processing function (callback function) has two parameters

      1. request
        1. The request object can be used to obtain some request information from the client
      2. response
        1. The response object can be used to send response information to the client
        2. There is a method: write can be used to send response data to the client
        3. write can be used multiple times, but end must be used in the end, otherwise the client will wait forever
    3. Bind the port number, start the server

    server.listen(3000,() => {
          
          
        console.log('服务绑定成功');
    })
    
  4. Run: Enter the current node js file in cmd or webStorm or software with terminal to run the service. Then enter the address in the browser window. In this example, port 3000 is set. You can visit http://localhost:3000/ to access the simple http service created by nodejs.

  5. End the service: close the current window or ctrl+c

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/114331316