美文网首页
Node.js原生加载静态文件(html或图片等)

Node.js原生加载静态文件(html或图片等)

作者: Hi小胡 | 来源:发表于2018-01-10 16:06 被阅读465次

代码:

html:

<img src="./public/a.jpg">

Nodejs:

var http = require('http');

http.createServer(function (req, res) {

    //获取文件类型
    var type = req.url.substr(req.url.length - 4, req.url.length);

    //获取资源路径
    var realpath = __dirname + '/public/';

    //加载需要显示的图片资源
    if (type == '.jpg') {
        res.writeHead(200, { 'Content-Type': 'text/'+type });
        res.end(fs.readFileSync(realpath + 'a.jpg'));
    }

    //加载静态html文件
    if (req.url == "/") {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(fs.readFileSync(__dirname + '/index.html'));
    }
}).listen(8080, function () {
    console.log("http://localhost:8080");
});

这样加载的html文件中的图片就能够显示了

相关文章

网友评论

      本文标题:Node.js原生加载静态文件(html或图片等)

      本文链接:https://www.haomeiwen.com/subject/itvonxtx.html