Express 中如何正确设置静态文件路径?

上官雅茹 阅读 2

我在用 Express 搭一个简单的前端页面,把 HTML 和 CSS 放在 public 文件夹里,但浏览器一直报 404 找不到样式文件。我明明用了 express.static 啊?

这是我的目录结构:

project/
├── app.js
└── public/
    ├── index.html
    └── style.css

这是我的 Express 配置:

const express = require('express');
const app = express();

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

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

app.listen(3000);

HTML 里引用 CSS 是这样写的:<link rel="stylesheet" href="style.css" rel="external nofollow" >,但打开页面时控制台显示 GET http://localhost:3000/style.css 404。到底哪里错了?

我来解答 赞 5 收藏
二维码
手机扫码查看
暂无解答

暂无解答