【node】创建web服务器的基本步骤

1:http模块创建服务器

//创建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');
})

注释:
在终端执行命令:node + 文件名 (node .\01-创建web服务器.js)
启动服务器

2:express框架

//先导入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');
})

服务器启动方式同上

1
vscode 为例,设置用户代码片段:
2

2
3
4
示例:
5
这里我编辑了express框架的代码片段,所以直接输入express,回车,可以快写出来创建服务器的大致框架

猜你喜欢

转载自blog.csdn.net/qq_43490212/article/details/113094731
今日推荐