1.url:
2.创建一个router.js文件,用于配置路由:
function login(res) { res.write('你已经登录了'); console.log('你已经登录了'); } function logOff(res) { res.write('你已经退出登录'); console.log('你已经退出登录'); } module.exports = { login, logOff }
3.调用路由
const log = require('./router.js'); const http = require('http'); //导入http const url = require('url') //导入url const hostname = '192.168.1.108'; //ip地址 随便写 如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址 const port = 3000; //端口号 const server = http.createServer((req, res) => { //创建一个server res.statusCode = 200; res.setHeader('Content-type', 'text/plain;charset = utf-8'); if (req.url !== '/favicon.ico') { //清除二次访问 console.log(url.parse(req.url)); const url_ = url.parse(req.url).pathname.replace(/\//g,''); //替换掉路由上的'/' console.log(url_); log[url_](res); res.end(); //用于关闭连接 } }); server.listen(port, hostname, () => { //监听server console.log(`服务器运行在http://${hostname}:${port}/`); });
此时在浏览器地址栏输入 http://192.168.1.108:3000/login 会得到 ‘你已经登录了’,若输入router.js中没有的,服务器就会报错崩溃;
4.路由优化
const log = require('./router.js'); const http = require('http'); //导入http const url = require('url') //导入url const hostname = '192.168.1.108'; //ip地址 随便写 如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址 const port = 3000; //端口号 const server = http.createServer((req, res) => { //创建一个server res.statusCode = 200; res.setHeader('Content-type', 'text/plain;charset = utf-8'); if (req.url !== '/favicon.ico') { //清除二次访问 console.log(url.parse(req.url)); const url_ = url.parse(req.url).pathname.replace(/\//g,''); //替换掉路由上的'/' console.log(url_); let true_url = trueUrl(url_); if(true_url){ log[true_url](res); }else{ res.write('没有找到该路径'); } res.end(); //用于关闭连接 } }); server.listen(port, hostname, () => { //监听server console.log(`服务器运行在http://${hostname}:${port}/`); }); //判读路由是否正确 function trueUrl(url) { if(typeof log[url] === 'undefined'){ return false; }else{ return url; } }