The histroy router is faulty

In History Router mode, we might do some routing refresh

The scenario is reproduced as follows:

Our route is under /route and is refreshed at this point.

Unfortunately, we have a 404.

This problem is very simple, because there is no corresponding API or static resources, so it is normal to return a 404 page.

You don’t want to add a backend API to return global index.html at this point, so you redirected the backpocket via webpack-dev-server’s historyFallback.

Refresh again:

Unfortunately, our refresh did not succeed, error:

Uncaught SyntaxError: Unexpected token '<'
Copy the code

Click on the error details to find the first line error

<! DOCTYPE html>Copy the code

Look at the request again, should not return script, why return an HTML?

The problem analysis

We did a loop through webpack-dev-server historyFallback to return all pages to /.

This would have been a good thing, as it would have allowed any request to return to the/page (i.e. our index.html) and then use our React router logic to distribute to the corresponding page.

But here’s where the problem lies. Let’s replay the browser and Webpack processing:

  1. The refresh/route
  2. Browser access/route
  3. webpack-dev-serverListen and return to/.
  4. At this time back/The correspondingindex.htmlpage
  5. To requestindex.htmlStatic resources in
  6. Here’s the bad news,index.htmlStatic resource bundles in are relative pathsbundle_xxxThat’s when the request arrives/route/bundle_xxx
  7. Normal browser processing/route/bundle_xxxContinue to request our server dev Server
  8. webpack_dev_serverthe/route/bundle_xxxAnd I redirect this path to/
  9. At this time back/The correspondingindex.html
  10. At this time/route/bundle_xxxReturned to theindex.html
  11. It is obvious that a bundle must be a JS file, and an HTML file is returned.

Problem solving

Knowing what the problem is, we solve it too easily.

The problem with step 6 is that our bundle files are packaged based on relative paths, so if we change it to an absolute path, we’ll be fine.

The solution

  • Dev: modifywebpackthepublicPathfor/Can be
  • Prod: modifypublicPathThe prefix is the corresponding deployment prefix

Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘ Uncaught SyntaxError: Unexpected Token ‘<‘

router

In addition, if you want to understand how spa application routing works, or if you don’t want to use a huge routing library like react-Router, check out Bobo-Router, which is a pure hooks matching library that supports route protection.