node.js入门学习(二)

一、构建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

猜你喜欢

转载自www.cnblogs.com/xy-ouyang/p/11110282.html