zoukankan      html  css  js  c++  java
  • node根据url跳转页面

    node根据url跳转页面

    fs模块--文件操作

    1. 异步读取
        fs.readFile( url , code , callback);

    2. 同步读取
        fs.readFileSync( url , code );

    var http = require('http');
    // url 做路径解析
    var url = require('url');
    // fs 读写文件
    var fs = require('fs');
    // node 服务
    var server = http.createServer();
    // 获取html相对路径
    var htmlDir = __dirname + '/html/';
    
    // 处理url请求的数据
    function sendData(file, req, res) {
        fs.readFile(file, function (err, data) {
            if (err) {
                res.writeHead(404, {
                    'content-type': 'text/html'
                });
                res.write('<h1>404<h1/>');
                res.end();
            } else {
                res.writeHead(200, {
                    'content-type': 'text/html'
                });
                res.write(data);
                res.end();
            }
        });
    }
    // 监听服务开启
    server.on('listening', function () {
        console.log('listen..');
    });
    server.on('request', function (req, res) {
        // 获取url后面的路径
        var urlStr = url.parse(req.url);
        switch (urlStr.pathname) {
            // localhost:8080/
            case '/':
                // 首页
                sendData(htmlDir + 'index.html', req, res);
                break;
            // localhost:8080/new
            case '/new':
                // 首页
                sendData(htmlDir + 'new.html', req, res);
                break;
            // localhost:8080/b
            default:
                sendData(htmlDir + 'error.html', req, res);
                break;
        }
    });
    server.listen(8026, 'localhost');
    
  • 相关阅读:
    Servlet三种实现方法(四)
    Tomcat 网站部署(三)
    MySQL表的增删改查和列的修改(二)
    Tomcat的目录结构(二)
    addEventListener,attachEvent
    DOM事件流
    函数内部的函数中的this都是指向window
    css3 translate属性
    parent,parents和closest
    each用法
  • 原文地址:https://www.cnblogs.com/Hsong/p/8992573.html
Copyright © 2011-2022 走看看