①.安装node运行环境
②.使用node.js创建软件层面上的网站服务器:要得到请求对象和响应对象。
1.1创建web服务器
// 引用系统模块
const http = require('http');
// 创建web服务器
const app = http.createServer();
// 当客户端发送请求的时候
app.on('request',(req,res) =>{ // request 事件名称 req是 request 的简写
// 响应
res.end('<h1>hi,user</h1>'); //res代表响应对象
});
// 监听3000端口
app.listen(3000);
console.log('服务器已启动,监听3000端口,请访问localhost:3000');
ps:node.js基于事件驱动的语言。(当什么时候,做什么事)。
添加请求语法:on('事件处理名称','事件处理函数');
当有请求来时,使用end()方法做出响应:end('响应内容');
监听端口语法:listen(端口号) // node开发习惯使用3000
验证代码:
新建文件夹server,其下新建文件app.js
const http = require('http');
const app = http.createServer(); // 网站服务器对象接收到app
app.on('request',(req,res) =>{ // 客户端有请求来时
res.end('<h2>hi,user</h2>'); // 只要有请求,就返回 hi,user
});
app.listen(3000); // 监听端口,向外界提供服务
console.log('服务器已启动,监听3000端口,请访问localhost:3000');
命令行工具:PS C:\Node\server> node app.js (使用nodemon app.js,好处只要修改了文件,命令行工具就会重新帮我们执行)
输出:网站服务器启动成功
浏览器中访问网站:localhost:3000
输出:<h2>hi,user</h2>