Express handles static resources (code demonstration)

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.

Use native Node code to process these static resources can refer to this blog:

How to deal with static resources in Node.js

But it is more troublesome. In the process of learning Node in, I believe we will go to study Expressframework (based on Node.js platform, fast, open, minimalist Web development framework). So how do we deal with these static resources in Express?


Two, the solution

Project structure
File structure
we use Express in express.staticthe built-in middleware functions. The features of this function are as follows:express.static(root, [options])

method one:

//第一个参数是请求路径url,当请求路径以 /public/ 开头的时候,就会去 ./public/ 请求对应的资源,
//如 http://localhost:3000/public/img/1.jpg
app.use('/public',express.static('./public/'))

The result is shown in the figure:Insert picture description here

Method Two:

We can achieve this effect: create a virtual path prefix for the files provided by the server (the path does not actually exist in the file system)

//第一个参数是什么,请求路径中就要加上,如 http://localhost:3000/a/img/1.jpg,可以把 a 当做 public 的别名
app.use('/a',express.static('./public/'))

//这样也是可以的 http://localhost:3000/a/b/c/img/1.jpg
app.use('/a/b/c',express.static('./public/'))

Method three:

When omitted app.use()when the first parameter, the request does not need to add the path / public / prefix or the other paths, direct path to write the resource public folder,

// http://localhost:3000/img/1.jpg
app.use(express.static('./public/'));

Of course we can also use absolute paths

// 提前导入 path 模块
app.use(express.static(path.join(__dirname, 'public')))

Complete code:

let express = require('express');

let app = express();

app.get('/',function (req,res) {
    
    
  res.send('我是首页');
})

app.use(express.static('./public/'));

app.listen(3000,function () {
    
    
  console.log('服务器启动成功: http://localhost:3000');
})

Three, summary

  1. If app.use()not the first argument, the direct use of resources in the public directory path
  2. If app.use()there is the first parameter, the first time to put the requested resource as a prefix is added to a parameter inside url

Four, extended reading

Express Chinese Network

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

If this article is helpful to you, please like it before leaving ( ̄▽ ̄)~*

Guess you like

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