node.js - Correct approach to handle react-routes on a server? -


i have uploaded application server , encountered problem.

going example.com displays homepage correctly, after doing example.com/dashboard error cannot /dashboard. assume because server trying path, still needs go through index.html single page app using react-router. believe need redirect requests got index.html make work, i'm not sure how can implement this. using express server files, here server.js

var express = require('express'); var app = express();  app.use(express.static(__dirname + '/dist'));  app.listen(8080, function() {   console.log('listening on port: ' + 8080); }); 

you need set express if request is not static file falls through , handled frontend route react app on index.html.

adding above example, this,

var express = require('express'); var app = express();  app.use('/static', express.static(__dirname + '/dist'));  app.get('*', function (req, res, next) {   if (req.path.startswith('/static')) return next()   res.sendfile('dist/index.html') })  app.listen(8080, function() {   console.log('listening on port: ' + 8080); }); 

notice added /static path static assets. means every request static asset app has /static/foo.jpg (or whatever). might worth renaming dist folder static too, keep names in sync.

this useful pattern because lets differentiate between request static asset, , request should fall through frontend app.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

dataset - MPAndroidchart returning no chart Data available -

post - imageshack API cURL -