node.js建立简单Http服务(四)

引入http基本模块实现服务

var http = require('http');
//文件读写模块
var fs = require('fs');
//路径相关模块
var path = require('path');

http.createServer(function(req, res){
    if(req.url === '/'){
        //输出内容并结束响应,这两行可以合成end('hello index')
        // res.write('hello index');
        // res.end();
        res.setHeader('Content-Type','text/plain; charset=utf-8');
        res.end('hello,<h1>我的主页</h1>');
    }else if(req.url === '/test'){
        //直接响应html
        res.setHeader('Content-Type','text/html; charset=utf-8');
        res.end('hello <h1>test</h1>');
    }else if(req.url === '/page'){
        //响应html文件
        //__dirname表示当前文件所在的文件夹绝对路径,__filename为当前文件绝对路径,非全局
        //类似于沙箱操作的参数(function(__dirname,__filename){...})('文件夹路径','文件路径')
        //path.join这一语句输出d:/nodespace/test/htmls/main.html,屏蔽了不同系统分隔符的区别
        //如果出现异常,err不为空
        fs.readFile(path.join(__dirname,'htmls','main.html'),function(err,data){
            //遇到异常直接抛出去
            if(err){
                throw err;
            }
            //把读取到的html文件直接返回给浏览器
            res.end(data);
        })
    }else{
        res.end('not found!')
    }
}).listen(8080, function(){
    console.log('server is running...')
})

加载静态资源文件,首先要安装mime模块,主要是根据后缀识别类型
安装和使用:https://www.npmjs.com/package/mime

image.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。