简体   繁体   English

express 是怎么知道这个路由的?

[英]How does express know this routing?

I create a simple express server and serve the static files我创建了一个简单的快速服务器并提供静态文件

const express = require('express');
const app = express();

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

app.listen(3000, () => {
console.log('Listening on port 3000')
})

When I head to localhost:3000, the index.html in my public directory renders for the route ' / '.当我前往 localhost:3000 时,我的公共目录中的 index.html 会为路由“/”呈现。 I didn't explicitly write the route in my index.js file.我没有在 index.js 文件中明确写出路由。 How does express know this? express 怎么知道这个?

I've tried changing the file name from index.html to random.html and I get an error.我尝试将文件名从 index.html 更改为 random.html,但出现错误。 CANNOT GET /不能获取 /

As mentioned in the comments, app.use(express.static('public')) is responsible for this.正如评论中提到的, app.use(express.static('public'))对此负责。 This will essentially serve all files in the public folder you have in the project.这基本上将为您在项目中拥有的public文件夹中的所有文件提供服务。 If you have an index.html in the public folder, then that will be served at the / endpoint automatically.如果您在public文件夹中有一个index.html ,那么它将自动在/端点提供服务。 This is a convention that most websites follow, and is documented in this SO post .这是大多数网站遵循的惯例,并记录在此 SO 帖子中

Here is the relevant documentation on express.static(...) : https://expressjs.com/en/starter/static-files.html这是有关express.static(...)的相关文档: https : //expressjs.com/en/starter/static-files.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM