当前位置:网站首页>Express - static resource request
Express - static resource request
2022-06-30 09:16:00 【The man of Jike will never admit defeat】
Express の Static resource requests
We talked about Download files , Actually, after talking about file downloading , You can handle static resources . Common static resource files include images ,CSS and JS file .
Use sendFile() Respond to static resource requests
const express = require('express');
const path = require('path');
const app = express();
app.get('/static/:file', (req, res) => {
let filename = req.params.file;
let options = {
root: path.join(__dirname, '../resource')
};
if (filename.indexOf('.css') !== -1) {
res.sendFile('index.css', options);
}
// .js .jpg Omit
});
app.listen(3000, () => {
console.log('server started ...');
});
Look ahead Download files This part , Otherwise, I'm afraid you'll have to guess what's going on in the code .
Such a request is no problem , The key is sendFile() Function is automatically set according to the file suffix Content-Type Response header for , Avoid us writing one more line of code 🤭

The problem now is , We use three if Deal with... Separately CSS,JS And picture type files . If one day you want to add a pair of PDF Handling of type , And at home if; If I don't want to deal with image type files anymore , Also delete one if. So this can , But not the best .
Use static middleware
One side , We all put all the static files in one directory , For example, below . If the user accesses /index.css,/index.js In this way, static resources can be returned directly . Use express.static(root, [options]) middleware .
Pay attention to directory deconstruction , We passed on to static The function is Relative paths Oh .
const express = require('express');
const app = express();
// The key
app.use(express.static('../resource'));
app.listen(3000, () => {
console.log('server started ...');
});
When we visit http://localhost:3000/index.js
Use multiple static resource directories
If we want to resource Create two folders under to store CSS, JS file , like this . Just call... More than once express.static() that will do .express It will find the static resource files according to the order in which directories are added in the code .
app.use(express.static('../resource/css'));
app.use(express.static('../resource/js'));

Create static resources URL Unified access path
If we want to access static resources in all URL add /static, like this ,http://localhost:3000/static/index2.js.
app.use(express.static('../resource');
app.use('/static', express.static('../resource/css'));
app.use('/static', express.static('../resource/js'));

See the code above , Specifying a prefix and not specifying a prefix can coexist . Look at the picture below , I didn't use it /static Prefix ~
Using absolute paths
my JS The files are written in node/express Under the table of contents , Static resources are stored in node/resource Next , So I am node/express Under boot node process , Accessing static resources is no problem . But if I was node Start the process under the directory , You won't find this file .

How to solve this problem ? The official website suggests that absolute paths are more secure .
app.use('/static', express.static(path.join(__dirname, '../resource/js')));
app.use('/static', express.static(path.join(__dirname, '../resource/css')));
This is normal 
options Parameters
options It's an object parameter , You can set a lot of values . I chose one that I felt was more useful , Others can see file , Although not everyone introduced 🤭
index attribute
Usually we visit a website , It is usually direct input http://localhost:3000 Jump to the home page , Instead of typing http://localhost:3000/index.html. So use index Sure . This property can receive strings or arrays .
app.use(express.static(path.join(__dirname, '../resource'), {
index: ['index.html']
}));

边栏推荐
- Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
- Talk about writing
- Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)
- Abstract factory pattern
- Detailed explanation of rect class
- 关于Lombok的@Data注解
- Concatapter tutorial
- [protobuf] protobuf generates cc/h file through proto file
- [paid promotion] collection of frequently asked questions, FAQ of recommended list
- [JPEG] how to compile JPEG turbo library files on different platforms
猜你喜欢

Abstract factory pattern

Bind threads to run on a specific CPU logical kernel

Small program learning path 1 - getting to know small programs

Occasionally, Flink data is overstocked, resulting in checkpoint failure

Pytorch BERT
![[wechat applet] realize applet pull-down refresh and pull-up loading](/img/23/2668a3a36fd46f63732c753fd6f237.jpg)
[wechat applet] realize applet pull-down refresh and pull-up loading

Interpretation of orientedrcnn papers

Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)

12. problem set: process, thread and JNI architecture

Handwriting sorter component
随机推荐
Deep Learning with Pytorch-Train A Classifier
Esp32 things (x): other functions
Unsupportedclassversionerror is reported when starting jar package. How to repair it
技术管理进阶——管理者如何进行梯队设计及建设
asdsadadsad
Is it safe to open an account? How can anyone say that it is not reliable.
Mmdet line by line code interpretation of positive and negative sample sampler
Use V-IF with V-for
【付费推广】常见问题合集,推荐榜单FAQ
Invalid update: invalid number of sections. The number of sections contained in the table view after
Research on lg1403 divisor
Rew acoustic test (IV): test principle of rew
List set export excel table
Set, map and modularity
ES6 learning path (II) let & const
Implementing custom drawer component in quick application
[JPEG] how to compile JPEG turbo library files on different platforms
Handwriting sorter component
Esp32 things (VIII): music playing function of function development
Concatapter tutorial