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');


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM