14

I am trying to manage a react app with react router and node js server

my router in react:

<BrowserRouter>
    <Switch>
        <PrivateRoute token={token} Component={Payments} exact path="/payments"/>
        <PrivateRoute token={token} Component={User} exact path="/user"/>
        <PrivateRoute token={token} Component={User} exact path=""/>
        <PrivateRoute token={token} Component={User} exact path="/"/>
    </Switch>
<BrowserRouter/>

export const PrivateRoute = ({Component, ...rest,token}) => {
    return (
        <Route {...rest} render={props => token ? (<Component {...props}/>) :
            (<Redirect to={{pathname: '/login', state: {from: props.location}}}/>)
        }/>
    )
};

and my router in my NodeJS Server :

const app = express();
const server = new Server(app);
const port = process.env.PORT || 5000;

app.use('/api', router);
app.use(express.static(path.join(__dirname, '/../react_dist')));
app.use('*',  (req, res) => {
    res.sendFile(path.join(__dirname, '/../react_dist', 'index.html'));
});
server.listen(port,() => {
    console.log('Server Is up : ', port)
});

when trying to access localhost:5000/user react app is working fine but when I want to access localhost:5000/api its redirected to the react app again cannot figure out how to fix it what do I need to change? thanks

5
  • 1
    try changing app.use('*', (req, res)=> { to app.use('/', (req, res)=> { Commented Sep 14, 2018 at 15:05
  • the problem is inside that switch of react router. you haven't defined the path for /api - which implies if you dont have token and your are trying to access some url it will revert back to react app Commented Sep 14, 2018 at 15:08
  • @VelimirTchatchevsky didnt help :/ Commented Sep 14, 2018 at 15:44
  • @karthik so how to handle route in side react router to node js ? <Route path="/api"/> Commented Sep 14, 2018 at 15:45
  • Make your port number different for both Commented Sep 15, 2018 at 6:58

4 Answers 4

15

You need to define Express routes and controllers to match the front-end request.

This is most likely invalid/not configured properly: app.use('/api',router);

Impossible to know for sure unless you paste what your router file looks like.

Try replacing it with the matching front-end request:

app.delete('/api', callbackfunction)
app.get('/api', callbackfunction)
app.put('/api', callbackfunction)
app.post('/api', callbackfunction)

Express needs a request (app.[request]), a route ('/api'), and a controller function (callback function).

app.get('/api', (req, res, done) => res.status(201).json({ message: "Hello World!" }));

app.use(express.static('client/build'));

app.get('*', (req, res) => res.sendFile(path.resolve('client', 'build', 'index.html')));

app.listen(5000);
Sign up to request clarification or add additional context in comments.

Comments

7

Solved !

because i created the react app with create-react-app cli i needed to add to package.json file this line :

"proxy": "http://localhost:5000"

and now when i am trying to make a GET request like that :

axios.get('/api/someurl') is working as expected

thank you all

1 Comment

i am having similar problem. My backend wirth build front in same directory, is requesting wrong routes. DO you know what's the problem?
3

What does your express route look like? Like the above user said, it really depends on what your router file looks like on the line

app.use('/api', router);

There is no need to define your API routes in react-router. However, I think you're misunderstanding how they work together. Usually react-router is used for client side routing while express handles your backend routes such as fetching data. You use react router to route users to different pages and views while your express routes would just render data.

Comments

0

my router :

const router = express.Router({});
router.get('/someurl',(res,req)=>{
       res.status(201).json({ message: "Hello World!" })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.