[英]express.js public folder not being recognised
我使用 Express 在 Node.js 中开发了一个简单的服务器,并且我设置了public
文件夹来提供 static 文件。
在我的根index.js
中,我有以下代码:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
http.listen(3000, () => console.log('started server on *:3000'));
目录结构是:
root
|---index.js
|---package.json
|---public
| |---index.html
| |---cs
| | |---index.css
| |---js
| | |---index.js
在public
文件夹中的index.html
中,我有以下代码:
<head>
<script src="js/index.js"></script>
<link rel="stylesheet" src="css/index.css" type="text/css" >
</head>
但是没有呈现 CSS。 我该如何解决这个问题?
尝试改变这个:
app.use(express.static(__dirname + '/public'));
对此:
app.use(express.static('public'));
将link
标签中的src
属性替换为href
。 如果这不起作用,请尝试以下解决方案。
我正在考虑您的服务器正在http://localhost:3000/
上运行
因此,通过附加基础index.html
在公共文件夹中的 index.html 的src
中更新 url,如下所示。
<head>
<script src="http://localhost:3000/js/index.js"></script>
<link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.