Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router how to redirect to server port

Hi I am using react router v4.

My React runs on port 3000, while express server runs on port 8080. The Redirect segment of the code below brings me to localhost:3000/http://localhost:8080/auth/login.

I have "proxy": "localhost:8080" in my React's package.json already. It doesn't work.

How can I redirect from localhost:3000 to localhost:8080/auth/login?

App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.props.fetchProducts();
    this.props.fetchUser();
  }

  render() {
    return (
      <Switch> 
        <Route exact path='/cart' render={() => this.props.isLoggedIn ? 
          <Checkout /> : 
          <Redirect to='http://localhost:8080/auth/login' /> 
        } />
        <Route exact path='/user/account/profile' render={() => <Profile />} />
        <Route exact path='/' render={() => <MainPage />} />
      </Switch>
    );
  }
}

Client's package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^3.6.2",
    "prop-types": "^15.6.2",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.3.1",
    "react-scripts": "^2.1.3",
    "redux": "^4.0.0",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.3.0"
  },
  "proxy": "http://localhost:8080",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

like image 508
jenlky Avatar asked Nov 06 '22 20:11

jenlky


1 Answers

Since I couldn't use react-router's Redirect to link to /auth/login, I changed window.location.href in a method and returned null.

class App extends Component {
  constructor(props) {
    super(props);
    this.props.fetchProducts();
    this.props.fetchUser();
  }

  redirect = () => {
    window.location.href = 'http://localhost:8080/auth/login';
    // maybe can add spinner while loading
    return null;
  }

  render() {
    return (
      <Switch> 
        <Route exact path='/cart' render={() => 
          this.props.isLoggedIn ? 
          <Checkout /> : 
          this.redirect()
        } />
        <Route exact path='/user/account/profile' render={() => <Profile />} />
        <Route exact path='/' render={() => <MainPage />} />
      </Switch>
    );
  }
}
like image 87
jenlky Avatar answered Nov 15 '22 04:11

jenlky