Alk
Alk

Reputation: 5547

Redirect from Express API Call in React App

I have a route defined in my React App which hosts the following component:

import { connect } from 'react-redux';
import _ from 'lodash';
import React, { PureComponent } from 'react';
import { actions as redirectActions } from '../../state/actions/redirect';

class MyRedirector extends PureComponent {
    componentDidMount() {
        const { redirect, match } = this.props;
        redirect(match.params.someData);
    }

    render() {
        return <div />;
    }
}

MyRedirector = connect(state => ({}), { ...redirectActions })(
    MyRedirector
);

export default MyRedirector;

I'm making a call to a backend API as follows:

const redirect = someData => async dispatch => {
    await axios
            .get(
                `${process.env.REACT_APP_API_URL}/api/someRoute/${someData}`,
                {}
            )
            .then(data => {})
            .catch(error => {
                console.log('ERROR', error);
            });

In this route, which is hosted on a Node.js express server, I run the following code:

 res.setHeader('Access-Control-Allow-Origin', req.get('origin'));
 res.redirect(
   new URL(
     `${req.get('origin')}/somePath/${
          someObject.data
        }/blabla?someQueryParam=${someData}`
   )
 );

The desired flow is as follows:

  1. User accesses my frontend route which hosts the redirect component
  2. Axios request made to backend
  3. Backend responds with redirect
  4. Frontend redirects user to redirect URL from backend

I'm not sure how to get this to work with the code above - in my network tab I see a 302 redirect from the API call, I also see an attempt to load the redirect URL, but that fails with a CORS error - no redirect on the page itself occurs.

I'm pretty sure there's a better way of achieving this.

Upvotes: 0

Views: 1417

Answers (1)

pageNotfoUnd
pageNotfoUnd

Reputation: 666

If you need to just route the user after a successful api call you can use history props from the react-router-dom

const redirect = someData => async dispatch => {
    await axios
            .get(
                `${process.env.REACT_APP_API_URL}/api/someRoute/${someData}`,
                {}
            )
            .then(data => {
               //check for the success case here using if
              this?.props?.history?.push(your desired url)
            })
            .catch(error => {
                console.log('ERROR', error);
            }); 

If you get any history/push is undefined you need to wrap the component in the HOC provided by the react-router-dom.

import {withRouter} from 'react-router-dom'; 

export default withRouter(MyRedirector);

Upvotes: 1

Related Questions