[Node] Basic steps to create a web server

1: http module creates server

//创建web服务器的基本步骤
// 1:导入http模块
const http = require('http')
//2:创建web服务器
const server = http.createServer()
//3:为服务器绑定request事件,监听客户端事件
server.on('request', (req, res) => {
    
    
    console.log('someone visit our web server');
})
//4:启动服务器
server.listen(1128, function () {
    
    
    console.log('The server starts up');
})

Note:
execute the command in the terminal: node + file name (node.\01-create web server.js) to
start the server

2: express frame

//先导入express包,终端执行 npm i [email protected](以这个版本号为例)
// 创建web服务器
// 导入express
const express = require('express')
//创建web服务器
const app = express()

//监听get事件,req:请求对象,res:响应对象
app.get('url', function (req, res) {
    
    
    // 处理函数
    res.send({
    
    
        name: 'zhao',
        age: 18
    })
})

//监听post事件
app.post('url', function (req, res) {
    
    
    res.send('请求成功')
})


//调用app.listen(端口号,回调函数)
app.listen(1128, function () {
    
    
    console.log('The server starts up');
})

The server startup method is the same as above

1
For example, vscode, set user code snippets:
2

2
3
4
Example:
5
Here I edited the code snippet of the express framework, so directly type express and press Enter to quickly write out the general framework for creating the server

Guess you like

Origin blog.csdn.net/qq_43490212/article/details/113094731