react-router only works for the root path

Viewed 152

I'm trying to route to multiple path using react router. But it only routes to the root path, not the others.

this is react code:

function Routing() {
    return (
        <Router>
            <div>
                <App/>
                <Switch>
                    <Route path = "/" exact component={App} />
                    <Route path = "/home" exact component={Home} />
                </Switch>
            </div>
        </Router>   
    )
}

however, it gives me: Cannot GET /home

After researching on internet i saw multiple people had the same issue, one of the answer from stacoverflow to solve this was using this code on the server.

app.get('*', function(req, res) {
  res.render('..build/index');
});

and:

app.get('*', function(req, res) {
      res.render('..public/index');
    });

and:

app.get('*', function(req, res) {
      res.render('index');
    });

but this gives me another error:

Error: No default engine was specified and no extension was provided.
    at new View (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/view.js:61:11)
    at Function.render (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/application.js:570:12)
    at ServerResponse.render (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/response.js:1012:7)
    at /Users/mhkhan4/Desktop/Books2Go/backend/server.js:17:7
    at Layer.handle [as handle_request] (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/layer.js:95:5)
    at /Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/index.js:281:22
    at param (/Users/mhkhan4/Desktop/Books2Go/backend/node_modules/express/lib/router/index.js:354:14)
1 Answers
if(process.env.NODE_ENV=="production"){
    app.use(express.static("client/build"))
    const path=require('path')
    app.get("*",(req,res)=>{
        res.sendFile(path.resolve(__dirname,'client','build','index.html'))
    })
}

You have to provide the correct directory name and the middleware to be used.While you are sending static files you should mention it to be static

Related