【问题标题】:express.static() doesn't route the static filesexpress.static() 不路由静态文件
【发布时间】:2019-03-21 17:03:27
【问题描述】:

在处理快速项目时,我正在尝试使用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

【问题讨论】:

  • 您确定要网址的src 部分吗?
  • index.jsstyle.css 位于 src 目录中

标签: javascript node.js express


【解决方案1】:

我只提供公用文件夹。

app.use(express.static(path.join(__dirname, 'public')));

那么你可以这样做:

http://localhost:8080/views/src/index.js

【讨论】:

  • 我已经删除了我的答案,因为这个最好,而不是一个一个设置静态文件。
【解决方案2】:

我已经解决了这个问题。

问题出在顺序错误,express.static() 一直在路由函数之后调用。

这是一个正确的版本:

app.use(express.static(path.join(__dirname, 'views', 'src')));
app.use(userRoutes);

【讨论】:

  • 这是有道理的。您的 app.js 位于公共目录中,使其成为应用程序的根目录。