0
点赞
收藏
分享

微信扫一扫

Nodejs Web网站-请求路径分发

const http = require('http'); // 加载 http 模块
//  req对象是Class: http.IncomingMessage的实例对象
//  res对象是Class: http.ServerResponse的实例对象
http.createServer((req,res)=>{
    // req.url可以获取URL中的路径(端口之后部分)
    res.end(req.url);
}).listen(3000,'192.168.43.43',()=>{  // 服务器 监听 192.168.43.43 的 3000端口
    console.log('服务启动...');
});

注:192.168.43.43 参数是 本地局域网分配的 ip地址(这个参数也可以省略不写)
windows 可通过 ipconfig 查看, Linux 可通过 ifconfig查看
如果省略ip,浏览器请求 http://localhost/ 即可。

运行结果:
浏览器请求 :http://192.168.43.43:3000/index.html
Nodejs Web网站-请求路径分发_linux
浏览器请求 :http://192.168.43.43:3000/vvcat.html
Nodejs Web网站-请求路径分发_html_02
浏览器请求 :http://192.168.43.43:3000/json.html
Nodejs Web网站-请求路径分发_linux_03

根据 res.end(req.url) 方法,我们可以进行请求路径分发操作

const http = require('http');
http.createServer((req,res)=>{
    if(req.url.startsWith('/index')){  // 根据 startsWith方法 来判断浏览器请求的文件名前缀
        // write向客户端响应内容,可以写多次
        res.write('Hello!');
        res.write('Welcome to home page');
        // end方法用来完成响应,只能执行一次
        res.end();  // 请求每一个页面必须有end结束,不管end中是否有内容
    }else if(req.url.startsWith('/login')){
        res.end('Welcome to the login page');
    }else{
        res.end('There are no other pages!'); 
    }
}).listen(3000,'192.168.43.43',()=>{
    console.log('服务启动...');
});

注:如果请求页面 没有 res.end();方法结束,会一直处于一个页面加载的状态。

运行结果:
浏览器请求 :http://192.168.43.43:3000/index.html
Nodejs Web网站-请求路径分发_客户端_04
浏览器请求 :http://192.168.43.43:3000/login.html
Nodejs Web网站-请求路径分发_linux_05
浏览器请求 :http://192.168.43.43:3000/vvcat.html
Nodejs Web网站-请求路径分发_html_06

解决使用中文页面乱码问题

const http = require('http');
http.createServer((req,res)=>{
    if(req.url.startsWith('/index')){
        res.writeHead(200,{
            'Content-Type':'text/plain; charset=utf8'  // 在浏览器中指定 utf8编码格式
        });
        // write向客户端响应内容,可以写多次
        res.write('你好!');
        res.write('欢迎来到index页面');
        // end方法用来完成响应,只能执行一次
        res.end();
    }else if(req.url.startsWith('/login')){
        res.writeHead(200,{
            'Content-Type':'text/plain; charset=utf8'
        });
        res.end('欢迎来到login页面');
    }else{
        res.writeHead(200,{
            'Content-Type':'text/plain; charset=utf8'
        });
        res.end('暂无其它页面');
    }
}).listen(3000,'192.168.43.43',()=>{
    console.log('服务启动...');
});

运行结果:
Nodejs Web网站-请求路径分发_linux_07
Nodejs Web网站-请求路径分发_html_08
Nodejs Web网站-请求路径分发_html_09


举报

相关推荐

0 条评论