Custom static route not working

后端 未结 1 1541
猫巷女王i
猫巷女王i 2021-01-16 09:45

Hi I am trying to establish my project in react. My Current project structure is

-public
--w
---dist
----bundle.js
---index.html
-server
--server.js
-src
--a         


        
1条回答
  •  有刺的猬
    2021-01-16 10:34

    You have to do some restructure

    -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
        }
    }
    

    You can keep your routes same.

    0 讨论(0)
提交回复
热议问题