-
-
Save ryanoglesby08/1e1f49d87ae8ab2cabf45623fc36a7fe to your computer and use it in GitHub Desktop.
/* | |
Incredibly simple Node.js and Express application server for serving static assets. | |
DON'T USE THIS IN PRODUCTION! | |
It is meant for learning purposes only. This server is not optimized for performance, | |
and is missing key features such as error pages, compression, and caching. | |
For production, I recommend using an application framework that supports server-side rendering, | |
such as Next.js. https://nextjs.org | |
Or, if you do indeed want a Single Page App, the Create React App deployment docs contain a lot | |
of hosting options. https://create-react-app.dev/docs/deployment/ | |
*/ | |
const express = require('express'); | |
const path = require('path'); | |
const port = process.env.PORT || 8080; | |
const app = express(); | |
// serve static assets normally | |
app.use(express.static(__dirname + '/dist')); | |
// handle every other route with index.html, which will contain | |
// a script tag to your application's JavaScript file(s). | |
app.get('*', function (request, response) { | |
response.sendFile(path.resolve(__dirname, 'index.html')); | |
}); | |
app.listen(port); | |
console.log("server started on port " + port); |
Hi @Ramandhingra,
Any server-side routing is done using standard Express features. Please check the docs for Express.
All client-side routing/rewriting/redirecting is done using React Router (or whatever client-side router you are using). Please check the docs for React Router.
In the future, please direct your questions to any of the community resources available, such as StackOverflow. https://www.reactiflux.com/ is a great learning tool for React. You could join the discord and ask questions there. Good luck!
Thank you so much for your reply and letting me know about these resources. In the future, if I have any questions, I will surely write over the discussion forums.
Hi @ryanoglesby08
what is the folder structure that is assumed that your project has, in order to use this piece of code ?
Thanks.
Thanks.
(Just realized you haven't posted on your blog in the past 4 years, considering the quality of your content, I recommend continuing it, I've subscribed through RSS.)
Hi @ryanoglesby08
One more query, Hope you'd answer.
Rewrites allow you to map an incoming request path to a different destination path. Next has built-in functionality for this. But how to implement it in React SPA.. just give an idea.
Source /api/*
Destination /index.html
Effect All requests → /index.html
Thanks