zoukankan      html  css  js  c++  java
  • node.js入门学习(二)MIME模块,request和response对象,demo之不同url请求不同html页面,页面包含图片、样式css等静态资源

    录:
    一、构建http服务程序-根据不同请求做出不同响应
    二、根据用户不同请求,读取不同HTML文件响应
    三、响应的HTML文件中包含图片的处理方式
    四、根据后缀查询MIME类型
    五、案例:不同url请求不同html页面,页面包含图片、样式css等静态资源
    六、request对象
    七、response对象常用成员(API)

    一、构建http服务程序-根据不同请求做出不同响应    <--返回目录

    // 加载http模块
    var http = require("http");
    
    // 创建一个http服务对象
    http.createServer(function(req, res) {
        if(req.url === '/') {
            res.end("hello index");
        } else if(req.url === '/list') {
            res.end("hello list");
        } else {
            res.end("404,not found!");
        }
    }).listen('8080', function() {
        console.log('服务器已经启动。');
    });

    二、根据用户不同请求,读取不同HTML文件响应    <--返回目录

      第一步:在D:/hello.js中写代码:

    // 加载http模块
    var http = require("http");
    var fs = require("fs");
    var path = require("path");
    
    // 创建一个http服务对象
    http.createServer(function(req, res) {
        if(req.url === '/') {
            fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else if(req.url === '/list') {
            fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else {
            res.end("404,not found!");
        }
    }).listen('8080',function() {
        console.log('服务器已经启动。');
    });

      第二步:在d盘下创建pages文件夹,在pages文件夹中添加index.html文件和list.html文件

      index.html(list.html把index替换成list)

    <!DOCTYPE html>
    <html>
    <head>
        <title>index页面</title>
        <meta charset="utf-8">
    </head>
    <body>
    <h2>index页面</h2>
    </body>
    </html>

      

      第三步:浏览器访问:http://localhost:8080/list

    三、响应的HTML文件中包含图片的处理方式    <--返回目录

      第一步:在D:/hello.js中写代码:

    // 加载http模块
    var http = require("http");
    var fs = require("fs");
    var path = require("path");
    
    // 创建一个http服务对象
    http.createServer(function(req,res) {
        if(req.url === '/') {
            fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else if(req.url === '/list') {
            fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else if(req.url.includes('.jpg')){
            fs.readFile(path.join(__dirname, 'images', req.url), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else {
            res.end("404,not found!");
        }
    }).listen('8080',function() {
        console.log('服务器已经启动。');
    });

      第二步:在d盘下创建pages文件夹,在pages文件夹中添加index.html文件和list.html文件

      index.html文件

    <!DOCTYPE html>
    <html>
    <head>
        <title>index页面</title>
        <meta charset="utf-8">
    </head>
    <body>
    <h2>index页面</h2>
    <img src="/1.jpg">
    </body>
    </html>

      第三步:在d盘下创建images文件夹,在images文件夹中添加1.jpg文件

      第四步:浏览器访问:http://localhost:8080

    四、根据后缀查询MIME类型    <--返回目录

      请求的静态资源可能是图片,可能是css等等,图片后缀可能是jpg,可能是png等等。为了写出通用的程序,可以使用第三方模块mime。

      使用第三方模块mime:

    // 根据请求后缀,来决定返回数据的MIME类型
    var mime = require("mime");
    res.setHeader('Content-Type', mime.getType(req.url));

    五、案例:不同url请求不同html页面,页面包含图片、样式css等静态资源    <--返回目录

      项目结构:

      

      在项目根目录node-hello下,执行npm install mime命令,下载安装mime模块;安装完后会在node-hello目录下创建node_modules目录。

      app.js

    // 加载http模块
    var http = require("http");
    var fs = require("fs");
    var path = require("path");
    var mime = require("mime");
    
    // 创建一个http服务对象
    http.createServer(function(req,res) {
        if(req.url === '/') {
            fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else if(req.url === '/list') {
            fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
                if(err) throw err;
                res.end(data);
            });
        } else if(req.url.includes('static')){
            fs.readFile(path.join(__dirname, req.url), function(err, data) {
                if(err) {
             res.end("文件不存在!");
             return;

           } res.setHeader('Content-Type', mime.getType(req.url)); res.end(data); }); } else { res.end("404,not found!"); } }).listen('8080',function() { console.log('服务器已经启动。'); });

      index.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>index页面</title>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="/static/css/common.css">
    </head>
    <body>
        <h2>index页面</h2>
        <img src="/static/images/1.jpg">
        <img src="/static/images/2.png">
    </body>
    </html>

      请求静态资源时,响应信息:

      如果不使用mime,并且将res.setHeader('Content-Type', mime.getType(req.url));注释掉,其实静态资源也能正常处理。

    六、request对象    <--返回目录

      1)request对象类型http.IncomingMessage,继承自stream.Readable;

      2)request对象常用成员
              - request.headers  获取所有的请求报文头,返回一个对象{'host':'localhost:8080', 'Connection':'keep-alive', ...}
              - request.rawHeaders  获取所有的请求报文头,返回一个数组 ['host','localhost:8080','Connection','keep-alive', ...]
              - request.httpVersion  获取客户端使用的http版本
              - request.method   请求是get还是post
              - request.url

    七、response对象常用成员(API)    <--返回目录

      1) response.write('数据',['数据编码'],[fn]);
      2) response.end();//结束响应
        
      3) response.end([data], [encoding], [callback]);
        - 该方法中如果指定了data,则相当于调用response.write(data,encoding)之后再调用response.end(callback)
        
      4) response.setHeader('','');//在响应内容前设置,设置响应报文头
        
      5) 设置http响应状态码和对应的消息
        response.statusCode=404
        response.statusMessage='Not Found';
        
      6) response.writeHead() 直接向客户端写入http响应报文头
         response.writeHead(404,'Not Found', {'Content-Type':'text/html;charset=utf-8'})

  • 相关阅读:
    Linux 下的类似Windows下Everything的搜索工具
    windows和linux环境下制作U盘启动盘
    程序调试手段之gdb, vxworks shell
    LeetCode 1021. Remove Outermost Parentheses (删除最外层的括号)
    LeetCode 1047. Remove All Adjacent Duplicates In String (删除字符串中的所有相邻重复项)
    LeetCode 844. Backspace String Compare (比较含退格的字符串)
    LeetCode 860. Lemonade Change (柠檬水找零)
    LeetCode 1221. Split a String in Balanced Strings (分割平衡字符串)
    LeetCode 1046. Last Stone Weight (最后一块石头的重量 )
    LeetCode 746. Min Cost Climbing Stairs (使用最小花费爬楼梯)
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/11110282.html
Copyright © 2011-2022 走看看