嗨,我正在尝试建立我的项目。 我当前的项目结构是
-public
--w
---dist
----bundle.js
---index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
我正在使用节点js作为服务器
我想在localhost:port//w/
上调用我的静态文件
和api呼叫localhost:port//api/
我尝试操纵server.js
,路线,项目结构和webpack.config
,但没有成功。
server.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>
)
}
任何人都可以建议我该怎么做或我在其中缺少什么吗?
答案 0 :(得分:0)
您必须进行一些重组
-public
--dist
---bundle.js
--index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
Server.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
}
}
您可以保持自己的路线不变。