'Routing is not working after createing of of react app in MERN app
I created a MERN app that has a node.js server. To host the website on Heroku first I have to create a build folder by it using npm run build. After that, I have to add this to my entry point file in my server
app.use(express.static("./FRONTEND/build"));
if (process.env.NODE_ENV == "production") {
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})
}
I use react-router-dom's BrowserRouter to routing through the webpages. But when I uploaded that site on Heroku I found out that the home page is working perfectly but when I route to other pages an error occurred and it says an error occurred in the application. I tried searching for it and found methods like adding static.json, using HashRouter, and adding .htaccess. But nothing works on my site.
Then, theoretically, I re-run the backend with my local computer, so the frontend is also hosted. The frontend was connected to the backend by this code.
app.use(express.static("./FRONTEND/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})
Hence, I was serving the build for the front-end and also found that routing is not working in the build also. And the error comes here is
ReferenceError: __dirname is not defined
at file:///D:/Yash/React_websites/housedeck-home-services/BACKEND/index.js:26:29
at Layer.handle [as handle_request] (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\layer.js:95:5)
at D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:281:22
at param (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:360:14)
at param (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:371:14)
at Function.process_params (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:416:3)
at next (D:\Yash\React_websites\housedeck-home-services\BACK
So, The routing is not working in the build index.html file. I want it to work any suggestions for that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|