[英]ExpressJS app.use
I'm trying to learn ExpressJS and I came across this piece of code. 我正在尝试学习ExpressJS,并且遇到了这段代码。 I just can't seem to understand the app.use function and the documentation is unclear to me.
我似乎无法理解app.use函数,并且文档对我来说还不清楚。 What exactly is happening to the /public directory in this particular example code when app.use is called?
调用app.use时,此特定示例代码中的/ public目录到底发生了什么?
// Require dependencies
var express = require('express');
var app = express();
// Set server port
app.set('port', (process.env.PORT || 3000));
// Set static page directory, /public
app.use(express.static(__dirname + '/public'));
app.use('/public', express.static('public'));
// Set template file directory, /views. Set view engine to EJS
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Route root request to pages/index
app.get('/', function(request, response) {
response.render('pages/index');
});
// Route favicon request to public/favicons
app.get('/favicon.ico', function(request, response) {
response.render('./public/favicons');
});
// Begin listening at specified port
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
It's simple - you are setting up the public directory to be accessible over HTTP. 很简单-您正在设置公共目录以通过HTTP进行访问。
So, something like http://localhost:3000/public/abc.jpg
will give you the abc.jpg
from the public folder. 因此,类似
http://localhost:3000/public/abc.jpg
将为您abc.jpg
来自公用文件夹的abc.jpg
。
The 该
app.use('/public', express.static('public'))
line simply means - match any path that starts with /public
like: 行的简单含义是-匹配以
/public
开头的任何路径,例如:
http://localhost/public/*.jpg
or any other extension - will choose that file from your public
(the argument in express.static('public')
) folder and serve it. 或其他任何扩展名-将从您的
public
文件夹express.static('public')
的参数)中选择该文件并提供服务。
The line 线
app.use(express.static(__dirname + '/public'))
means - match any path and if file found in public
directory, serve it over HTTP. 表示-匹配任何路径,如果在
public
目录中找到文件,则通过HTTP进行投放。
You can just use of the these two lines - difference being the /public
part in the URL. 您可以只使用这两行-区别在于URL中的
/public
部分。
The docs are quite clear about this: https://expressjs.com/en/starter/static-files.html 该文档对此非常清楚: https : //expressjs.com/en/starter/static-files.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.