13.网站外链资源的加载

1. 网站外链资源的加载

网站在加载的时候,首先加载的是页面,然后,遇到link、script、img、iframe、video、audio等带有src或者href等属性的标签(外链资源标签)的时候,浏览器会自动对这些资源发起新的请求。

例:

  • 首先,创建一个index.html
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="item">
        <div class="wrap">
            <img src="/public/img/timg1.jpg" alt="">
        </div>
        <h4>虞美人·听雨</h4>
        <p>少年听雨歌楼上,红烛昏罗帐。</p>
        <p>壮年听雨客舟中,江阔云低,断雁叫西风。</p>
        <p>而今听雨僧庐下,鬓已星星也。</p>
        <p>悲欢离合总无情,一任阶前点滴到天明。</p>
    </div>
    <div class="item">
        <div class="wrap">
            <img src="/public/img/timg2.jpg" alt="">
        </div>
        <h4>阮郎归</h4>
        <p>山前灯火欲黄昏,山头来去云。</p>
        <p>鹧鸪声里数家村,潇湘逢故人。</p>
        <p>挥羽扇,整纶巾,少年鞍马尘。</p>
        <p>如今憔悴赋招魂,儒冠多误身。</p>
    </div>
</body>
</html>
  • 然后,创建一个getStatic.js文件
**getStatic.js**

const http = require('http');
const fs = require('fs');
http.createServer(function(request, response) {
    let url = request.url;
    if(url == '/') {
        fs.readFile('./index.html', function(error, data) {
            if(error) {
                return response.end('404 not found.')
            }
            response.end(data);
        })
    }
}).listen(8080, function() {
    console.log('Server is running...')
})

注意:上面的写法是简写,创建一个服务器,这个服务器会自动绑定request请求事件,然后返回一个服务器对象,所以可以在接着调用listen方法

  • 接着在命令行执行getStatic.js文件
PS E:\good good study\NodeJs\source> node .\getStatic.js
Server is running...
-
  • 最后,在浏览器输入localhost:8080
image.png
  • 网络页面


    image.png
  • 通过上面的图片可以发现,localhost网页加载成功,返回200,但是网页中还有两张图片,这是因为浏览器加载完网页之后,会自上往下执行,遇到外链资源标签就会在次发起请求,由于我们只处理了/这个路径,所以加载没有成功。所以我们在修改一下我们的getStatic.js文件

思路:我们可以定义一个public文件夹,将一些静态的资源统一放到这个文件夹当中,然后将这个文件夹暴露出去,让它的url路径,就变成它的文件路径即可

getStatic.js文件修改如下:

**getStatic.js**

const http = require('http');
const fs = require('fs');
http.createServer(function(request, response) {
    let url = request.url;
    if(url == '/') {
        fs.readFile('./index.html', function(error, data) {
            if(error) {
                return response.end('404 not found.')
            }
            response.end(data);
        })
    }else if(url.startsWith('/public/')) {
        fs.readFile('.'+url, function(error, data) {//别忘记文件路径前面加个点
            if(error) {
                return response.end('404 not found...');
            }
            response.end(data);
        })
    }
}).listen(8080, function() {
    console.log('Server is running...')
})
  • 然后命令行窗口运行,接着在浏览器输入localhost:8080
image.png
image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容