javascript - 自定义静态路由不起作用
问题描述
嗨,我正在尝试在反应中建立我的项目。我当前的项目结构是
-public
--w
---dist
----bundle.js
---index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
我正在使用节点 js 作为服务器,我希望调用我的静态文件并调用localhost:port//w/
apilocalhost:port//api/
我尝试过操纵server.js
、路线、项目结构,webpack.config
但未能成功。
服务器.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public/w');
app.use(express.static(publicPath));
app.get('/w/*', (req, res) => {
console.log('Calling..');
res.sendFile(path.join(publicPath, 'index.html'));
})
app.get('/api/test', (req, res) => {
res.send("Hello");
})
app.listen(port, () => {
console.log(`Server is up on ${port}`);
})
webpack.config
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public', 'w', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public', 'w'),
publicPath: '/dist/',
historyApiFallback: true
}
}
我的路线
const AppRouter = (props) => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" component={Dashboard} />
<Route path="/w/resume-builder" component={ResumeBuilder} />
</Switch>
</div>
</BrowserRouter>
)
}
谁能建议我应该做什么或我在其中缺少什么?
解决方案
你必须做一些重组
-public
--dist
---bundle.js
--index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
服务器.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public');
app.use(express.static(publicPath));
//keep all api before fallback
app.get('/api/test', (req, res) => {
res.send("Hello");
});
app.get('/w/*', (req, res) => {
console.log('Calling..');
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log(`Server is up on ${port}`);
});
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
publicPath: '/dist/',
historyApiFallback: true
}
}
你可以保持你的路线不变。
推荐阅读
- node.js - 如何从 afterUpsert 钩子中获取更新后的续集模型的实例?
- css - 如何消除 MailChimp ul 中的子弹
- node.js - 处理在 NodeJS、Express 中以类似方式开始的不同路由
- ios - 快速将 BLE 特征值转换为字符串
- mongodb - Mongodb仅返回数组中的匹配元素
- python-3.x - python glob.glob 不再工作,返回一个空列表
- druid - 德鲁伊规范截断和加载德鲁伊
- asp.net - 带有许多参数的 ASP.NET CORE 路由
- mysql - SQL Lag() 查找日期时间差异
- featuretools - 使用高级原语?