首页 > Web开发 > 详细

07-Node.js学习笔记-路由

时间:2019-12-20 11:50:48      阅读:91      评论:0      收藏:0      [点我收藏+]

路由

http://localhost:3000/index
http://localhost:3000/login
//路由是指客户端请求地址与服务器端程序代码的对应关系。简单的说,就是请求什么响应什么。
//当客户端发来请求的时候
app.on('request',(req,res)=>{
    //获取客户端的请求的路径
    let {pathname} = url.parse(req.url);
    if(pathname =='/'||pathname=='/index'){
        res.end('欢迎来到首页');
    }else if(pathname=='/list'){
        res.end('欢迎来到列表页面');
    }else{
        res.end('抱歉,您访问的也能出游了');
    }
});
//1.引入系统模块http
//2.创建网站服务器
//3.为网站服务器对象添加请求事件
//4.实现路由功能
 //a.获取客户端的请求方式
 //b.获取客户端的请求地址


const http = require('http');
const url = require('url');
const app = http.createServer();
app.on('request',(req,res)=>{
    //判断请求方式
    const method = req.method.toLowerCase();
    //获取请求地址
    const pathname = url.parse(req.url).pathname
    //响应报文处理
    res.writeHead(200,{
        'content-type':'text/html;charset=utf8'
    })
    if(method=='get'){
        if(pathname=='/'||pathname=="/index"){
            res.end('欢迎来到首页')
        }else if(pathname=='/list'){
            res.end('欢迎来到列表页')
        }else{
            res.end('对不起,您访问的页面不存在')
        }
    }else if(method=='post'){
        if(pathname=='/'||pathname=="/index"){
            res.end('欢迎来到首页0')
        }else if(pathname=='/list'){
            res.end('欢迎来到列表页0')
        }else{
            res.end('对不起,您访问的页面不存在0')
        }
    }


});
app.listen(3000);
console.log('服务器启动成功')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  
    <form action="http://localhost:3000" method="post">
        <input type="text" name="uname">
        <input type="password" name="password">
        <input type="submit">
    </form>
</body>
</html>

07-Node.js学习笔记-路由

原文:https://www.cnblogs.com/foreverLuckyStar/p/12071946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!