[英]Express serve static files inside Router
我目前正在研究一個nodejs
項目,我有一個簡單的問題。 我想將node_modules
文件夾中的一些庫靜態地提供給客戶端(可能很愚蠢,但與問題無關),但我不想將我的主服務器 JS 文件與所有這些靜態提供的文件一起node_modules
,如下所示:
const express = require('express');
const app = express();
// Imports here
app.use('/assets/lib/bootstrap', './node_modules/bootstrap/dist');
app.use('/assets/lib/axios', './node_modules/axios/dist');
app.use('/assets/lib/aos', './node_modules/aos/dist');
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
如果我有 10 個以上的導入,這會破壞我的 Server JS 文件,我希望盡可能保持干凈。 我想知道為什么這個選項不起作用:
./routes/route1.js
:
const express = require('express');
const router = express.Router();
const path = require('path');
// Imports here
router.use('/bootstrap', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/axios', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/aos', path.resolve(__dirname, 'node_modules/aos/dist'));
// path to node_modules file is not the problem here
module.exports = router
在我的主服務器 JS 文件中:
const express = require('express');
const app = express();
const route1 = require('./routes/route1');
// Imports here
app.use('/assets/lib', route1);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
但這給了我一個錯誤。 該文件不是靜態提供給客戶端的。 這是因為快速路由器不能提供靜態文件嗎? 也許這是一個新手錯誤,但任何幫助表示贊賞。 第一個代碼片段確實有效,但我正在努力使我的代碼井井有條。
在 route1.js 文件中使用 express.static 中間件,而不是簡單地將文件夾路徑字符串傳遞給路由。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.