当前位置:网站首页>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']
}));

边栏推荐
- 127.0.0.1, 0.0.0.0 and localhost
- Find the number that appears only once in the array
- Talk about how the kotlin collaboration process establishes structured concurrency
- About Lombok's @data annotation
- 使用华为性能管理服务,按需配置采样率
- Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
- Interviewer: do you understand the principle of recyclerview layout animation?
- Using appbarlayout to realize secondary ceiling function
- Mmcv expanding CUDA operator beginner level chapter
- [protobuf] protobuf generates cc/h file through proto file
猜你喜欢

ES6 learning path (III) deconstruction assignment

Talk about the job experience of kotlin cooperation process

Flutter 0001, environment configuration

Applet learning path 2 - event binding

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which

Introduction to the runner of mmcv

Pytorch BERT
![[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.](/img/77/eb66ec83b34c251e732d495fbaa951.jpg)
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.

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

Esp32 (4): overview of the overall code architecture
随机推荐
What are the SQL add / delete / modify queries?
Dart basic notes
Resnet50+fpn for mmdet line by line code interpretation
Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"
Interpretation of source code demand:a rotation equivariant detector for aerial object detection
Deep Learning with Pytorch-Train A Classifier
启动jar包报错UnsupportedClassVersionError,如何修复
Design specification for smart speakers v1.0
ES6 learning path (IV) operator extension
Detectron2 source code reading 3-- encapsulating dataset with mapper
Coredata acquisition in swift sorting, ascending, descending
Sort (simple description)
Qt连接神通数据库
Abstract factory pattern
Get to know handler again
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Icon resources
Interpretation of orientedrcnn papers
Talking about the difference between kotlin collaboration and thread