避免Express.Js添加页面url到文件path的行为
我正在使用node.js
和express.js
服务我的前端代码。
在这里,我正面临着我在不同页面URL上的script src
提供的文件path的问题。
我的项目文件结构如下:
react_jsx/ dst/ index.html styles.css main-62a2a28f9255e698905d.js // creating this file using a bundler.
styles.css
和main-62a2a28f9255e698905d.js
都使用webpack
捆绑器dynamic添加到index.html
。 但正确添加为<link href="style.css" rel="stylesheet"></head>
和<script type="text/javascript" src="main-62a2a28f9255e698905d.js"></script>
节点服务器代码如下:
const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.resolve(__dirname, 'react_jsx/dst'))); app.use(express.static(path.resolve(__dirname))); // app.use('/react_jsx/dst',express.static(path.join(__dirname, ''))); app.use(express.static(path.join(__dirname, ' '))); app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, 'react_jsx/dst/index.html')); }); const PORT = process.env.PORT || 9000; app.listen(PORT, () => { console.log(`App listening on port ${PORT}!`); });
该网页在基本url上正常工作。 即,在localhost:9000
。
但是,当我更改页面URL时,文件的path也会改变。 假设如果Url页面是localhost:9000/app/login
, styles.css
和main-[hash].js
的path也会改变。
文件path变为localhost:9000/app/login/styles.css
和localhost:9000/app/login/main-[hash].js
我该如何解决? 我经历了很多的答案,并解决了一些其他文件path的问题,但无法解决位于index.html的同一文件夹中的文件的问题
如下所示,在html中为域根提供相对path。
<link href="/style.css" rel="stylesheet"></head> <script type="text/javascript" src="/main-62a2a28f9255e698905d.js"></script>
添加到webpackconfiguration
output: { publicPath: "/" }
我想,你可以使用路由 。
喜欢 :
var router = express.Router(); app.use('/app/login', router);