本文共 1226 字,大约阅读时间需要 4 分钟。
路由是指客户端请求地址与服务器端程序代码的对应关系
实现路由的步骤:// 1.引入系统模块httpconst http = require('http');//2.创建网站服务器const app = http.createServer();const url = require('url')// 导入系统模块querystring用于将HTTP参数转换为对象格式const querystring = require('querystring');// 3.为网站服务器对象添加请求事件app.on('request', (req, res) => { //获取请求方式 并将其转换为小写 //1.获取客户端的请求方式 const method = req.method.toLowerCase(); //2.获取客户端的请求地址 const pathname = url.parse(req.url).pathname; res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' }); if (method === 'get') { if (pathname === '/' || pathname == '/index') { res.end('欢迎来到首页'); } else if (pathname == '/list') { res.end('欢迎来到列表页') } else { res.end('您访问的页面不存在') } } else if (method == 'post') { let postData = ''; // 监听参数传输事件 req.on('data', (chunk) => postData += chunk); // 监听参数传输完毕事件 req.on('end', () => { console.log(querystring.parse(postData)); }) }});// 设置端口app.listen(3000);console.log("该服务器已开启");//4.实现路由功能
积极的心态和确切的目标是走向一切成就的起点。我必须把自己的目标牢记在心里,用积极的心态,指挥我的思想,控制我的情绪,掌握自己的命运!
转载地址:http://skvv.baihongyu.com/