0

I'm new in the world of web development and I have a problem that seems dumb but it's taking me a lot of time.

I've made an express server that runs React in the front end. I run both (react and express server) by parsing my react app with webpack and bundle, then I load the output files with express static using the public dir.

That's how i can render the html doc at the root path ('/'). The problem begins when I try to use react-router with express router. I've been looking to solve this problem and I found that I only have to set an express route that looks like this:

/*This is my actual code in the project*/

router.get('/*', (req, res, next) =>{
res.sendFile(require('../public/index.html'))
})

This code will run react because I'm calling it from the script tag inside the html and React will handle the url and render it's own components.

But when I try to get to any path on the browser, I get most simple error ever, SynthaxError:

C:\Users\Matthew\Desktop\Proyectos\Apid0\src\public\index.html:1
<!DOCTYPE html>
^

SyntaxError: Unexpected token '<'
at wrapSafe (internal/modules/cjs/loader.js:1067:16)
at Module._compile (internal/modules/cjs/loader.js:1115:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Module.require (internal/modules/cjs/loader.js:1040:19)
at require (internal/modules/cjs/helpers.js:72:18)
at C:\Users\Matthew\Desktop\Proyectos\Apid0\src\routes\index.js:5:18
at Layer.handle [as handle_request] 
(C:\Users\Matthew\Desktop\Proyectos\Apid0\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Matthew\Desktop\Proyectos\Apid0\node_modules\express\lib\router\route.js:137:13)

Can someone help me to handle this problem?

2 Answers2

1

I fixed the problem with this:

router.get('/*', (req, res, next) =>{
res.sendFile('index.html', { root: path.join(__dirname, '../public') });
})
0

Firsly you should read file contents as a string (not require).

Something like:

router.get('/*', (req, res, next) =>{
  fs.readFile("../public/index.html", "utf8", function(err, data) {
    if (err) throw err;
    res.sendFile(data)
  })
})
Dmitry Weiner
  • 96
  • 1
  • 3