node.js(三)----路由

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;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值