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
For example, vscode, set user code snippets:
Example:
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