Home > Blockchain >  React browser router getting syntax error unexpected token '<'
React browser router getting syntax error unexpected token '<'

Time:09-15

I have a react website that works fine locally and uses react browser router. When I build it and place the build folder on my hosted webhost (dreamhost) The routing to other pages does not work. The app.js

    <Router>
      <Header />
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="/contact" element={<ContactPage />} />
      </Routes>
      <Footer />
    </Router>

I followed this guide: https://www.andreasreiterer.at/fix-browserrouter-on-apache/

Which suggested adding an .htaccess file with

    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

So after adding the htaccess file with those lines, my hosted react website now correctly routes to pages (whereas before it was a 404). The only problem is now when I go to those pages I just get console errors that say:

2.6c645178.chunk.js:1 Uncaught SyntaxError: Unexpected token '<' (at 2.6c645178.chunk.js:1:1)
main.2e7dd33a.chunk.js:1 Uncaught SyntaxError: Unexpected token '<' (at main.2e7dd33a.chunk.js:1:1)
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

Based on things I found online, it sounds like it is treating the pages as html and not recognizing it as javascript. Does anyone have any advice for how I might solve this? Suggestions I saw mentioned adding the lang= to the script tag. But in my react app I don't have any script tag.

CodePudding user response:

  1. Please go through react router docs and search for basename prop on Router component

  2. The error you are getting is maybe somewhere your JSON isn't being parsed properly. try locating JSON.parse() in your code and see if you can fix it somehow

CodePudding user response:

I figured out the solution. After trying adding a basename (as suggested by one commentor) I realized the routing was working because the pages worked in the subdirectory with the base name.

It turned out on homepage in the package.json I just had to add a "/". So instead of "homepage" : "http://website.com" I changed it to http://website.com/.

Before I had "homepage": "." Because certain guides had suggested putting that there when deploying to a webserver so it used any folder. Apparently I had to have my websites public URL, along with the / at the end to fix the routing.

  • Related