React-router urls don't work when refreshing or writing manually

前端 未结 30 2711
时光取名叫无心
时光取名叫无心 2020-11-21 05:07

I\'m using React-router and it works fine while I\'m clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in

相关标签:
30条回答
  • 2020-11-21 05:30

    As I am using .Net Core MVC something like this helped me:

        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                var url = Request.Path + Request.QueryString;
                return App(url);
            }
    
            [Route("App")]
            public IActionResult App(string url)
            {
                return View("/wwwroot/app/build/index.html");
            }
       }
    

    Basically in MVC side, all the routes not matching will fall into to Home/Index as it specified in startup.cs. Inside Index it is possible to get the original request url and pass it wherever needed.

    startup.cs

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
    
                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
    
    0 讨论(0)
  • 2020-11-21 05:30

    If you are hosting in IIS ; Adding this to my webconfig solved my problem

    <httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
        <remove statusCode="500" subStatusCode="100" />
        <remove statusCode="500" subStatusCode="-1" />
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" path="/" responseMode="ExecuteURL" />
        <error statusCode="500" prefixLanguageFilePath="" path="/error_500.asp" responseMode="ExecuteURL" />
        <error statusCode="500" subStatusCode="100" path="/error_500.asp" responseMode="ExecuteURL" />
    </httpErrors>
    

    You can make similar configuration for any other server

    0 讨论(0)
  • 2020-11-21 05:31

    Using HashRouter worked for me with Redux also, just simply replace:

    import {
      Router //replace Router
    } from "react-router-dom";
    
    ReactDOM.render(
        <LocaleProvider locale={enUS}>
        <Provider store={Store}>
            <Router history={history}> //replace here saying Router
                <Layout/>
            </Router>
        </Provider>
    </LocaleProvider>, document.getElementById("app"));
    registerServiceWorker();
    

    to:

    import {
      HashRouter //replaced with HashRouter
    } from "react-router-dom";
    
    ReactDOM.render(
        <LocaleProvider locale={enUS}>
        <Provider store={Store}>
            <HashRouter history={history}> //replaced with HashRouter
                <Layout/>
            </HashRouter>
        </Provider>
    </LocaleProvider>, document.getElementById("app"));
    registerServiceWorker();
    
    0 讨论(0)
  • 2020-11-21 05:36

    Looking at the comments on the accepted answer and the generic nature of this question ('don't work'), I thought this might be a good place for some general explanations about the issues involved here. So this answer is intended as background info / elaboration on the specific use case of the OP. Please bear with me.

    Server-side vs Client-side

    The first big thing to understand about this is that there are now 2 places where the URL is interpreted, whereas there used to be only 1 in 'the old days'. In the past, when life was simple, some user sent a request for http://example.com/about to the server, which inspected the path part of the URL, determined the user was requesting the about page and then sent back that page.

    With client-side routing, which is what React-Router provides, things are less simple. At first, the client does not have any JS code loaded yet. So the very first request will always be to the server. That will then return a page that contains the needed script tags to load React and React Router etc. Only when those scripts have loaded does phase 2 start. In phase 2, when the user clicks on the 'About us' navigation link for example, the URL is changed locally only to http://example.com/about (made possible by the History API), but no request to the server is made. Instead, React Router does its thing on the client side, determines which React view to render and renders it. Assuming your about page does not need to make any REST calls, it's done already. You have transitioned from Home to About Us without any server request having fired.

    So basically when you click a link, some Javascript runs that manipulates the URL in the address bar, without causing a page refresh, which in turn causes React Router to perform a page transition on the client side.

    But now consider what happens if you copy-paste the URL in the address bar and e-mail it to a friend. Your friend has not loaded your website yet. In other words, she is still in phase 1. No React Router is running on her machine yet. So her browser will make a server request to http://example.com/about.

    And this is where your trouble starts. Until now, you could get away with just placing a static HTML at the webroot of your server. But that would give 404 errors for all other URLs when requested from the server. Those same URLs work fine on the client side, because there React Router is doing the routing for you, but they fail on the server side unless you make your server understand them.

    Combining server- and client-side routing

    If you want the http://example.com/about URL to work on both the server- and the client-side, you need to set up routes for it on both the server- and the client side. Makes sense right?

    And this is where your choices begin. Solutions range from bypassing the problem altogether, via a catch-all route that returns the bootstrap HTML, to the full-on isomorphic approach where both the server and the client run the same JS code.

    .

    Bypassing the problem altogether: Hash History

    With Hash History instead of Browser History, your URL for the about page would look something like this: http://example.com/#/about The part after the hash (#) symbol is not sent to the server. So the server only sees http://example.com/ and sends the index page as expected. React-Router will pick up the #/about part and show the correct page.

    Downsides:

    • 'ugly' URLs
    • Server-side rendering is not possible with this approach. As far as Search Engine Optimization (SEO) is concerned, your website consists of a single page with hardly any content on it.

    .

    Catch-all

    With this approach you do use Browser History, but just set up a catch-all on the server that sends /* to index.html, effectively giving you much the same situation as with Hash History. You do have clean URLs however and you could improve upon this scheme later without having to invalidate all your user's favorites.

    Downsides:

    • More complex to set up
    • Still no good SEO

    .

    Hybrid

    In the hybrid approach you expand upon the catch-all scenario by adding specific scripts for specific routes. You could make some simple PHP scripts to return the most important pages of your site with content included, so Googlebot can at least see what's on your page.

    Downsides:

    • Even more complex to set up
    • Only good SEO for those routes you give the special treatment
    • Duplicating code for rendering content on server and client

    .

    Isomorphic

    What if we use Node JS as our server so we can run the same JS code on both ends? Now, we have all our routes defined in a single react-router config and we don't need to duplicate our rendering code. This is 'the holy grail' so to speak. The server sends the exact same markup as we would end up with if the page transition had happened on the client. This solution is optimal in terms of SEO.

    Downsides:

    • Server must (be able to) run JS. I've experimented with Java i.c.w. Nashorn but it's not working for me. In practice it mostly means you must use a Node JS based server.
    • Many tricky environmental issues (using window on server-side etc)
    • Steep learning curve

    .

    Which should I use?

    Choose the one that you can get away with. Personally I think the catch-all is simple enough to set up, so that would be my minimum. This setup allows you to improve on things over time. If you are already using Node JS as your server platform, I'd definitely investigate doing an isomorphic app. Yes it's tough at first, but once you get the hang of it it's actually a very elegant solution to the problem.

    So basically, for me, that would be the deciding factor. If my server runs on Node JS, I'd go isomorphic; otherwise I would go for the Catch-all solution and just expand on it (Hybrid solution) as time progresses and SEO requirements demand it.

    If you'd like to learn more on isomorphic (also called 'universal') rendering with React, there are some good tutorials on the subject:

    • React to the future with isomorphic apps
    • The Pain and the Joy of creating isomorphic apps in ReactJS
    • How to Implement Node + React Isomorphic JavaScript & Why it Matters

    Also, to get you started, I recommend looking at some starter kits. Pick one that matches your choices for the technology stack (remember, React is just the V in MVC, you need more stuff to build a full app). Start with looking at the one published by Facebook itself:

    • Create React App

    Or pick one of the many by the community. There is a nice site now that tries to index all of them:

    • Pick your perfect React starter project

    I started with these:

    • React Isomorphic Starterkit
    • React Redux Universal Hot Example

    Currently I am using a home-brew version of universal rendering that was inspired by the two starter kits above, but they are out of date now.

    Good luck with your quest!

    0 讨论(0)
  • 2020-11-21 05:36

    For those who are using IIS 10, this is what you should do to make this right. Be sure that you are using browserHistory with this. As for reference I will give the code for the routing, but this is not what matters, what matters is the next step after the component code below:

    class App extends Component {
        render() {
            return (
                <Router history={browserHistory}>
                    <div>
                        <Root>
                            <Switch>
                                <Route exact path={"/"} component={Home} />    
                                <Route path={"/home"} component={Home} />
                                <Route path={"/createnewproject"} component={CreateNewProject} />
                                <Route path={"/projects"} component={Projects} />
                                <Route path="*" component={NotFoundRoute} />
                            </Switch>
                        </Root>
                    </div>
                </Router>
            )
        }
    }
    render (<App />, window.document.getElementById("app"));
    

    Since the problem is IIS receives request from client browsers, it will interpret the URL as if it is asking for a page, then returns a 404 page since there is no available page. Do the following:

    1. Open IIS
    2. Expand Server then open the Sites Folder
    3. Click the website/application
    4. Go to the Error Pages
    5. Open the 404 error status item in the list
    6. Instead of the option "Insert content from static file into the error response", change it to "Execute a URL on this site" and add "/" slash value to the URL.

    And it will now work fine.

    I hope it helps. :-)

    0 讨论(0)
  • 2020-11-21 05:37

    If you are using Create React App:

    There's a great walk though of this issue with solutions for many major hosting platforms that you can find HERE on the Create React App page. For example, I use React Router v4 and Netlify for my frontend code. All it took was adding 1 file to my public folder ("_redirects") and one line of code in that file:

    /*  /index.html  200
    

    Now my website properly renders paths like mysite.com/pricing when entered into the browser or when someone hits refresh.

    0 讨论(0)
提交回复
热议问题