How to deal with static resources in Node.js

Handling static resources

1. Problem description

After the browser receives the HTML content returned by the server, it will start parsing from top to bottom. During the parsing process, if it finds:

  • link
  • script
  • img
  • iframe
  • video
  • audio

When the href attribute tag with src or link is attached, the browser will automatically initiate a new request for these static resources . We need to process these new requests


2. Solution

In order to handle these static resources in a unified manner, we agreed to store all static resources in the public directory for the purpose of unified processing

  • If the request path starts with /public/ , the server thinks that you want to obtain a resource in public, so we can directly read the request path as the file path

3. Code demonstration

(1) File structure
File structure
(2) index.html file

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
  <link rel="stylesheet" href="/public/lib/bootstrap.css">
  <link rel="stylesheet" href="/public/css/main.css">
</head>
<body>
<h1>灰太狼</h1>
<img src="/public/img/1.jpg">
</body>
</html>

  • Note: In the server, do not write relative paths in the file path . Because at this time, all resources are obtained through URL identification.
  • Server open /public/ directory
  • So the request path in the code is written as: /public/xxx
  • / Here is the meaning of the url root path.
  • When the browser actually sends a request, it will finally splice the URL to http://127.0.0.1:3000

(3) app.js file

If we don’t deal with those static resources, let’s see what happens.

let http = require('http');
let fs = require('fs');

http.createServer(function (request,response) {
    
    
  console.log("服务器收到请求");
  let url = request.url;
  if (url === '/') {
    
    
    fs.readFile('./views/index.html',function (err,data) {
    
    
      if (err) {
    
    
        response.end('404');
        return;
      }
      response.end(data)
    })
  }
}).listen(3000,function () {
    
    
  console.log('http://127.0.0.1:3000');
})

Use to node app.jsstart the server, visit http://127.0.0.1:3000 , open the console, the result is as shown in the figure. The reason is that we did not write code to process these static resources, and the server could not read them, so they could not be returned to the browser. Rewrite app.js below

result
(4) app.js (processing static resources)

//app.js文件

let http = require('http');
let fs = require('fs');

http.createServer(function (request,response) {
    
    
  console.log("服务器收到请求");
  let url = request.url;
  if (url === '/') {
    
    
    fs.readFile('./views/index.html',function (err,data) {
    
    
      if (err) {
    
    
        response.end('404');
        return;
      }
      response.end(data)
    })
  } else if (url.indexOf('/public/') !== -1) {
    
    
     //此处是关键,当发现请求路径中含有 /public/,我们把请求路径当作文件路径来直接进行读取
    fs.readFile('.' + url,function (err,data) {
    
    
      if (err) {
    
    
        response.end('404');
        return;
      }
      response.end(data);
    })
  }
}).listen(3000,function () {
    
    
  console.log('http://127.0.0.1:3000');
})
  • All our static resources are placed in the public folder, so there will be /public/ before the request path of the resource
  • So if the request path starts with /public/ , the server thinks you want to get a resource in public, we can directly read the request path as the file path
    Insert picture description here

We restart node app.js, visit http://127.0.0.1:3000 , and the result is shown in the figure. Refresh, the page will be displayed immediately. Open the console to see that all resources have been requested.
Insert picture description here

4. Node learning resource recommendation

Further reading
https://blog.csdn.net/weixin_43974265/category_10692693.html

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/111761878