I have a website made with React running on Digital Ocean with pm2 and NGINX. The entry point "/" loads just fine but when I try to go to the "/:username" route I just get 404 Not Found. My routes are defined in App.jsx as follows:
<Switch>
<Route
exact path='/'
render={
routeProps => <Front {...routeProps} />
}
/>
<Route
path='/:username'
render={
routeProps => <Profile handleSignOut={ this.handleSignOut } {...routeProps} />
}
/>
</Switch>
index.js has the following code:
ReactDOM.render(<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
)
The routes all work as expected when running locally with npm run start.
This is a very common problem for single page apps written in different frameworks like React or Angular.
The problem, though, is irrelevant to the frameworks. It rather lies in the mechanism that is the in-browser routing. It is actually not a real routing. When you open a single page app, a simple index.html file is served, and when you navigate away inside the app, the framework takes care of rendering a new page and faking a navigation event (so that it will be recorded in the browser history and the url is changed).
But when you arrive on a subadress, like 'myapp.com/some-page', this will mke the server try and serve an actual directory called 'myapp.com/some-page', not your index.html file, which you obviously need to run the app, and, as this directory does not exist, it will throw a 404 error.
To fix this, you need to reconfigure your server, so that in case of a 404 error, instead of failing, it returns your index.html file; this way your code will be loaded and the underlying framework will handle the routing to display the correct page.
For react App hosted on app Platform on Digital Ocean.
Luckily now, you can now enable it through the UI. Please follow the steps below and it should be resolved.
Using Cloud panel UI: Log in and click on App > Settings >> click on component name > scroll down to Custom page > Edit Custom page and select Catchall > Enter index.html in the page name block > Save
Cheers,Arinze Hills
In addition to #amem nice explanation, add the following line to your web server configuration file:
For NGINX add error_page 404 /index.html;
For Apache add ErrorDocument 404 /index.html to your .htaccess
Related
I'm seeing an issue on Heroku that I'm not having trouble with locally. I've seen various articles and other SO posts that address this issue, and I've got an understanding that it has something to do with properly configuring the static.json file in my app in order for heroku to properly handle front end react routing, but I'm having some real trouble resolving this.
I'm using the following buildpacks and confirmed they're installed via the Heroku Dashboard > Settings:
https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/static.tgz
https://github.com/mars/create-react-app-buildpack
Using a gin-gonic server and serving up ./web to serve the frontend as specified by my .Dockerfile
I have the following static.json:
{
"root": "build/",
"routes": {
"/**": "index.html"
},
"clean_urls": false,
"https_only": true,
"headers": {
"/**": {
"Strict-Transport-Security": "max-age=31557600"
}
}
}
My project structure is as follows:
/app
- /main.go
- /server
-- /server package .go files...
- /client
-- /public
-- /src
-- /remaining react related files and assets...
I have tried having the static.json file in the app root, as well as in the client dir to no avail. Still seeing 404s if I refresh on or navigate from an external site to anything but the homepage.
So, none of the static.json solutions that I found while researching this issue seemed to work. From what I gather this appears to be a known issue with react routing and/or Heroku.
That being said, if this is helpful for anyone else that comes across this issue, this is how I addressed it:
Set up a NotFound handler on the server:
All this NotFound handler do is serve up your index.html file allowing your SPA framework to handle the routing itself (making the determination if valid or truly not found).
I achieved this in go/gin-gonic by:
e := gin.New()
// gin engine set up...
e.NoRoute(func(ctx *gin.Context){
ctx.File("./web")
})
Reason being - when you hit your app normally (via the base url) you're app will serve up index.html, and then and subsequent clicks from within the app are handled via the SPA routing. But if you navigate to any other route directly (i.e. manually going to https://<your domain>.com/foo in the address bar) You will be bypassing the SPA routing and going directly to the server. This case is also achieved by simply refreshing any page other than the homepage as well.
So by serving up the index.html when you hit a not found on the server you are re-enabling the SPA framework to work its magic and serve up that route if its valid which is what we want, but also be able to handle the 404 by...
Wiring up a NotFound component in the React App:
I achieved this in React by making a simple component and wiring up a Route to consume it by registering it to path="*" as a catch all after defining all other routes:
<Router basename="/">
<Route exact path="/foo">
<FooView />
</Route>
<Route exact path="/">
<HomeView />
</Route>
<Route path="*">
<NotFoundView />
</Route>
</Router>
I am trying to run my ReactJS build on wp engine hosting, where my WordPress site is already residing. I have placed my ReactJS build on the root along with other folders such as wp-admin, wp-content, wp-includes.
My ReactJS build is placed in a folder named calculator. My React App URL looks like this http://xyz.blahblah.com/calculator/ When I launch this URL, It works normally in the flow but I am unable to open any of my React Route directly from the web browser.
When I try to open any other route directly such as http://xyz.blahblah.com/calculator/recomendations It takes me to the WordPress site page not found page. How to fix this? So that I can open any route of my ReactJS App.
Below is my React App routing code:
<BrowserRouter basename="/calculator">
<Switch>
<Route path="/" exact component={QuestionsWrapper} />
<Route path="/recomendations" component={Recomendations} />
</Switch>
</BrowserRouter>
I have built an app that doesnt have a server. It just pulls data from a couple of endpoints.
When someone tries to access a page that isnt the root URL they receive a Page not found message.
I havent managed to find a solution to this that doesnt involve writing a server. Im really hoping that I can avoid that because the app really is too simple to need it.
When I navigate to http://url.com/nextPage it returns a Page not found, but if I navigate there from the root http://url.com/ I dont have any issues.
I have not pushed an app to production before so this was an unexpected issue, but it is also important to how the app works that users are able to access a page directly via the URL.
My App.tsx file. Both pages are just straight forward React.
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Route
path='/'
exact
component={HomePage}
/>
<Route
path='/nextPage'
component={NextPage}
/>
</Router>
)
}
Since now I know you are using Netlify as your hosting provider, there is a way to do it without having your own server. Netlify has lots of configuration, one of it being redirects.
You could try adding to your Netlify.toml the following:
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Or, you could create a _redirects file, with the following content:
/* /index.html
Take a look at this documentation: https://www.netlify.com/blog/2019/01/16/redirect-rules-for-all-how-to-configure-redirects-for-your-static-site/
I created a ReactJS project with the create-react-app package and that worked well, also I'm starting the application using npm start command.
So the application is landing on http://localhost:3000 by default, but I wanted to configure my landing URL to something like this http://localhost:3000/google where /google will be useful to configure the apache web server to detect my application.
NOTE: There is a way to redirect using react-router-dom to <Redirect from="/" to="/google" /> option and this will work once the application is loaded. But I am expecting my application should be accessible only with this URL http://localhost:3000/google. That means all my webpack, node_modules, public URL should go via /google only.
How to configure the base URL of web application ?
I think you have the answer to your question here: React Start Landing URL
The first one by #Bhojendra Rauniyar
Hope it helps!
If you are using react-router you can use the basename prop to set the sub directory
<BrowserRouter basename='/google'>
<App />
</BrowserRouter>
OR you can redirect / to /content in your Switch block
<Switch>
<Redirect exact from="/" to="/google" />
<Route exact path="/google" component={ContentComponent} />
</Switch>
I builded a little questionnaire with React and React-router v4.
I developed with create-react-app.
It is working fine when I build it as standalone page. The Router routes like I want.
But now I made a build for a page in Mahara (https://mahara.org/) and another one for Wordpress.
In Mahara it is a plugin and the questionnaire comes in a part of the Mahara page.
In Wordpress the questionnaire is a part of the whole Wordpress Page.
In both variants the router doesn't work. The path "/" is not found. So the default "not found" page appears.
I edited the homepage property in the package.json and the basename attribute for the BrowserRouter.
Is it generally possible to make the router functioning, when the React app is not a standalone page?
Maybe the problem is, that in both platforms(Mahara/Wordpress) the url is not really the one where the questionnaire exists?
In mahara for example the questionnaire exists in "http://mahara_17_10.local/blocktype/learningstyle/js/build/" but the url shows: "http://mahara_17_10.local/view/view.php?id=3842". This public page is generated with Smarty templating and some php.
I tried both: The real place, where the React build folder exists, or the generated url (the second one). But I had no luck so far.
here some code:
package.json:
"homepage": "http://mahara_17_10.local/view/view.php?id=3842",
BrowserRouter:
<BrowserRouter basename="/view/view.php?id=3842">
Router in Main Component:
<div className={ApplicationClassNames}>
<ApplicationHeader
title={title}
count_blocks={count_blocks}
number_of_blocks_overall={number_of_blocks_overall}
/>
<Switch>
<Route exact path='/' render={() => (
<ApplicationBody
page_now={page_now}
count_cats={count_cats}
count_pages={count_pages}
categories_pages_quantity={categories_pages_quantity}
catValuesCountAll={catValuesCountAll}
language={language}
show_result={false}
values_not_for_categories={values_not_for_categories}
/>
)}/>
<Route path='/wtf' component={Result} />
<Route><div>Not found</div></Route>
</Switch>
</div>
So my questions are:
1: Is it generally possible to make the router functioning, when the React app is not a standalone page?
If yes, how for excample in wordpress or mahara. Maybe anybody knows a tutorial oder something else what can help me here.
I would be very happy, if somebody could help me here a little bit.
thanx =)
# Learner
If you have a Moodle Plugin (as a react application) on a public page for example, and the url is : moodlepage.de/mod/learningstyle/view.php?id=27
you can put an .htaccess file in the root folder of moodle with the following content:
Options -MultiViews
RewriteEngine On
RewriteRule ^mod/learningstyle/view.php/(.*)$ /mod/learningstyle/view.php?id=27 [QSA,L]
This tells the webserver to look at /mod/learningstyle/view.php?id=27 when you type mod/learningstyle/view.php/green for eyample. So the page is called and react has its url with the paramters.
This is the minimal configuration of the htaccess. You can put there rewrite conditions and some other stuff. But this works.
The (.*)$ is for the router paramters. They work too.
Make sure you have Allowoverride All in your virtual host or whereever you have your settings for the webserver.
This works fine in moodle and mahara. Worpress has its own htaccess with some rewriterules, so it didnt work for me. See here:
React Router v4 and htaccess with wordpress