简体   繁体   中英

React application on node express server - how to route

I have simple express server in node:

const express = require('express')
const path = require('path')
const application = express()
const port = process.env.PORT || 80

const PUBLIC_DIR = 'public'

application.use(express.static(path.join(__dirname, PUBLIC_DIR)))
application.listen(port)

//handle 404
application.use((req, res) => {
    res.send('404: Page not Found', 404)
});

//handle 500
application.use((error, req, res, next) => {
    res.send('500: Internal Server Error', 500)
});

console.log(['HTTP server running on ', process.env.HOST, ' / ', port].join(''))

When I put "builded" react app into folder public, server return index.html good. But problem is in react routers.

I have routers like this:

/
/home
/about

When I go to url localhost/ - works fine, return index html with full app, but problem is when I go to /home, /about, server return 404, how to fix it? How to redirect to react route? I hope you understand me.

Thank you for any help

Try to return all the routes from index.html as follows:

const express = require('express')
const path = require('path')
const application = express()
const port = process.env.PORT || 80

const PUBLIC_DIR = 'public'

application.use(express.static(path.join(__dirname, PUBLIC_DIR)))
application.listen(port)

app.use(express.static('client/build'));  //use your build path my build path under the root folder is client/build
  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client','build', 'index.html')); //use your build path my build path under the root folder is client/build
  });

//handle 404
application.use((req, res) => {
    res.send('404: Page not Found', 404)
});

//handle 500
application.use((error, req, res, next) => {
    res.send('500: Internal Server Error', 500)
});

console.log(['HTTP server running on ', process.env.HOST, ' / ', port].join(''))

after you build the react try using :-

app.use(require('body-parser').json({ limit: '50mb' }));
app.use(require('body-parser').urlencoded({ limit: '50mb', extended: true, parameterLimit: 1000000 }));
app.use(express.static(path.join(__dirname, '../client')));


switch (process.env.NODE_ENV) {
    case 'production':
        app.use(express.static('./client/build/'));
        app.use('/', express.static('./client/build/index.html'));
        break;
    default:
        app.use(express.static('./client/'));
        app.use(express.static('./', config.staticOptions));
        app.use('/', express.static('./client/index.html'));
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM