node express中的use的方法

var app = express();
app.use("/", () => {});
这种写法为什么所有的请求都会走这个函数,比如我访问http://localhost:8080/a.html,还是会进入上面的函数,这个函数的意思不是我访问http://localhost:8080/才会进入的吗?
app.use("/a", () => {});
我访问http://localhost:8080/a.html就不会进入
再提问的过程中我好想明白了,这http://localhost:8080/a.html这种写法是访问根目录下的a.html,而http://localhost:8080/s/a.html是访问跟目录下的s目录下的a.html页面,我的理解对吗?

阅读 4.5k
2 个回答

不對。如果你想要的是訪問文件,你應該使用靜態路由

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

在此,public即為你的根目錄


app.use是引入中間件用的,設置路由應該使用app.get()app.post()app.putapp.route

路由路徑與請求方法一起定義了請求的端點,路由路徑可以是字符串、字符串模式或正則。

Refer to the Expross Guide Routing for more information.

app.use

解释:挂载中间件用的,默认挂载在根目录/,你理解成路由了,所以存在偏差。
Mounts the middleware function(s) at the path. If path is not specified, it defaults to “/”.
A route will match any path, which follows its path immediately with a “/”. For example: >app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题