[英]express.static() doesn't route the static files
在處理Express項目時,我正在嘗試使用express.static()
函數。
我在主文件中添加了一條靜態路由:
app.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const ApiResponse = require('./utils/response');
const userRoutes = require('./routes/lottery');
const app = express();
app.use(bodyParser.json({ extended: false }));
app.use(userRoutes);
app.use(express.static(path.join(__dirname, './', 'views', 'src', 'index.js')));
app.use(express.static(path.join(__dirname, './', 'views', 'src', 'style.css')));
app.use((err, req, res, next) => {
ApiResponse.error(res, err);
});
app.listen(8080);
lottery.js(router.js)
const express = require('express');
const path = require('path');
const LotteryController = require('../controllers/LotteryController');
const router = express.Router();
router.get('/', (req, res, next) => {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
router.post('/simulate', LotteryController.simulate);
router.all('*', (req, res, next) => {
const err = new Error('message: Endpoint not found');
err.status = 404;
next(err);
});
module.exports = router;
加載localhost:8080頁面時,我的index.js和style.css文件未連接,並顯示以下錯誤:
GET http:// localhost:8080 / src / index.js net :: ERR_ABORTED 404(未找到)
這是我的項目文件夾的樹:
public
├───views
| └───src
| | ├─── style.css
| | └─── index.js
| |
| └─ index.html
|
└───app.js
我只提供公用文件夾。
app.use(express.static(path.join(__dirname, 'public')));
然后,您可以執行以下操作:
http://localhost:8080/views/src/index.js
我已經解決了問題。
問題是順序錯誤,在路由函數之后express.static()已被調用。
這是正確的版本:
app.use(express.static(path.join(__dirname, 'views', 'src')));
app.use(userRoutes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.