After building the application, if you open the site in the root in production, then everything will be fine. As you navigate the site, everything works great.
This is what source looks like:
But if I try to go to a url different from the root, for example, /profile
, then react just breaks:
Nothing is displayed on the screen and the source is strange.
I created the application using the create-react-app
.
This is how I send the application from the server:
if (process.env.NODE_ENV === 'production') {
app.use('/', express.static(path.join(__dirname, 'client', "build")));
app.get('*',
async(req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
}
);
}
errors:
(just in case)
App.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
// Pages
import Main from './Pages/Main/Main';
import Auth from './Pages/Auth/Auth';
import Profile from './Pages/Profile/Profile';
import Blog from './Pages/Blog/Blog';
import CreateBlog from './Pages/CreateBlog/CreateBlog';
import PostPage from './Pages/PostPage/PostPage';
import BlogsAndUsers from './Pages/BlogsAndUsers/BlogsAndUsers';
// Components
import Header from './Components/Header/Header';
function App() {
return (
<Router>
<div className="notification-bar"></div>
<Header />
<Switch>
<Route path='/' exact>
<Main />
</Route>
<Route path='/auth' exact>
<Auth />
</Route>
<Route path='/blog/:id' exact>
<Blog />
</Route>
<Route path='/blogs' exact>
<BlogsAndUsers type="blogs" />
</Route>
<Route path='/profiles' exact>
<BlogsAndUsers type="profiles" />
</Route>
<Route path='/create_blog' exact>
<CreateBlog />
</Route>
<Route path="/profile/:id" exact>
<Profile />
</Route>
<Route path="/article/:id" exact>
<PostPage />
</Route>
<Redirect to='/' />
</Switch>
</Router>
);
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import './fonts/fonts-import.css'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
This is how it looks: https://i.stack.imgur.com/2xqxX.gif
Has anyone faced a similar problem? How can you decide?
Top comments (0)