当前位置:网站首页>用Node创建一个服务器

用Node创建一个服务器

2022-06-21 16:04:00 玉安_ZhangDe

1、导入 http 模块

// 1、导入http模块
const http = require('http')

2、创建 web 服务器实例

// 2、创建web服务器实例
const server = http.createServer()

3、为服务器实例绑定 request 事件,监听客户端的请求

// 3、为服务器绑定request事件
server.on('request',(req,res)=>{
    // req.url 获取请求地址 默认是/
    const url = req.url
    console.log(url);
    // req.method 获取请求的方式  get/post
    const method = req.method
    console.log(method);

    // res.end() 服务器向客户端响应内容 暂不支持中文
    res.end('Hello world!')
})

4、 启动服务器

// 4 、启动服务器
server.listen(80,()=>{
    console.log('server running at http://localhost');
})

运行结果示意

 

安装配置NodeJs环境

如若想实现上述功能,首先需要安装配置NodeJs环境,我把链接放在这里,请前往菜鸟教程去看具体的教程,这里我就不多做赘述了。

Node.js 安装配置 | 菜鸟教程 (runoob.com)

原网站

版权声明
本文为[玉安_ZhangDe]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_47373340/article/details/125361987