Local development of React-router-dom and local services (node, webpack)

Source: Internet
Author: User
Scene


Use react to do development and avoid using React-router


React Router is already a V4 version.


React RouterNow it has been divided into three packages:react-router,react-router-dom,react-router-native.
The React Router application provides the core routing components and functions, while the other two packages provide the components of the specific environment (the browser and the react-native corresponding platform), but they also export the React-router exported modules again.


> The core of this article is the story of React-router-dom and local services


react-router-domAs the platform of the browser, is our web preferred to do.react-router-domcan select<BrowserRouter>and<HashRouter>component



<BrowserRouter>Should be used in projects where the server processes dynamic requests (know how to handle arbitrary URIs)
<HashRouter>Used to process static pages (only requests that request known files).



If there is a Link tag, click to jump to/test/guide.



Browserrouter:http://localhost:8080/test/guide
Hashrouter:http://localhost:8080/#/test/guide



Generally, it is more recommended to use


About local services


Today, front-end development avoids local service development, and most will choose node as the Local service development layer, including koa,express. Webpack do Local Service Webpack-dev-server (also an express service)
Local routing is not avoided with local services. How do get URL requests for local services fit with React-router? Please look down.


About Hashrouter and local services


Hashrouter do local development, mainly hash address, hash address refers to the URL after the # number. This feature will only implement static page jumps, will not produce the change of the route
As the above example Hashrouter:http://localhost:8080/#/test/guidefor the server, the route is actually the root directory '/', and "#/test/guide" is only the hash address, can be viewed through the browser location command
Because for the service side, the route does not actually have a GET request change, so that the server does not respond, there will be no cannot get page hint 404 and other issues.



If it is a webpack service, there are a lot of articles about setting up thehistoryApiFallback:trueInternet, giving this answer to deal with local service problems



The first thing to dodevServer.historyApiFallbackis to respond to a specific page when you return to page 404.



If you modify the Output.publicpath value by default to '/' in the Webpack configuration file, then you need to declare the request redirect and configure the Historyapifallback.index value.


// output.publicPath: '/assets/'historyApiFallback: { index: '/assets/'}

About Browserrouter and local services
by the example above Browserrouter:http://localhost:8080/test/guide, Visible, With Browserrouter,historyprocesses the URL link, and if the page is refreshed and reload after the link jumps, the Local service
captures the GET request for the route, which is the key to the problem. There are many ways to require local services to handle requests, and here is a more general and straightforward approach;

Const router = express.Router();
Const request = require("request-promise").defaults({ jar: true });

Router.all("*", async (req, res, next) => {
    Let url = req.url; //url on page link
    Let html = "";

    // Does not match the following routing rules, only matches URL GET requests
    If (url.match(/\.(png|jpe?g|gif|js|css|html|ico)/)) {
        Return next();
    }

    Html = await reactRoute().catch(e => {
      //do error handle
      Return false;
    });

    If(html){
        Return res.send(html);
    }

    //Other routing rules...
    Return next();
})


Async function reactRoute() {
  Return new Promise((resolve, reject) => {

    / / Here you can do a layer of non-react project filtering, not important here
    // if(noReact){
    // reject('no react url')
    // }

    Let html = await request({
      Method: "get",
      Url: `http://localhost:8080/pages/index.html` //local service index path (BrowserRouter path configured for react), depending on the project, just an example
    }).catch(e => {
      Reject(e);
    });

    Resolve(html);
  })
} 


The logic of the above code is that the local service, read the URL get request, if the Local service request 404, then put the React browserrouter boot file back, the file should be the local service can read to the HTML file.
The following is a schematic





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.