-
引入http模块
let http = require('http');
-
创建服务实例
let server = http.createServer();
-
等待请求
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);// 发送响应并结束响应(更常用) })
-
当客户端请求时,会自动触发服务器的request请求事件,然后调用回调函数
-
请求处理函数(回调函数)有两个参数
- request
- 请求对象可以用来获取客户端的一些请求信息
- response
- 响应对象可以用来给客户端发送响应信息
- 有一个方法:write可以用来给客户端发送响应数据
- write可以使用多次,但是最后一定要使用end,否则客户端会一直等待
- request
-
绑定端口号,启动服务器
server.listen(3000,() => { console.log('服务绑定成功'); })
-
-
运行:在cmd或者webStorm或者拥有terminal的软件中输入node 当前js文件,即可运行服务。接着在浏览器窗口输入地址,本示例设置的是3000端口,则访问http://localhost:3000/即可访问nodejs创建的简单的http服务。
-
结束服务:关闭当前窗口或者ctrl+c
Nodejs创建简单的http服务
猜你喜欢
转载自blog.csdn.net/chen__cheng/article/details/114331316
今日推荐
周排行