Javascript express.static()不';t路由静态文件
在处理express项目时,我尝试使用Javascript express.static()不';t路由静态文件,javascript,node.js,express,Javascript,Node.js,Express,在处理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('./
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);
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;
lotket.js(router.js)
当我加载localhost:8080页面时,我的index.js和style.css文件没有连接,并显示以下错误:
获取网络::ERR_中止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
http://localhost:8080/views/src/index.js我已经解决了这个问题 问题的顺序是错误的,express.static()在路由函数之后一直在调用 以下是正确的版本:
app.use(express.static(path.join(__dirname, 'views', 'src')));
app.use(userRoutes);
你确定要url的
src
部分吗?index.js
和style.css
位于src目录下我删除了我的答案,因为这是最好的答案,而不是逐个设置静态文件。这很有意义。您的app.js位于公共目录中,使其成为应用程序的根目录。