reactjs - React-router如何重定向到服务器端口

标签 reactjs react-router

嗨,我正在使用 React Router v4。

我的 React 在端口 3000 上运行,而 Express 服务器在端口 8080 上运行。下面代码的重定向段将我带到 localhost:3000/http://localhost:8080/auth/login

我的 React 的 package.json 中已经有 "proxy": "localhost:8080" 。这不起作用。

如何从 localhost:3000 重定向到 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>
    );
  }
}

客户端的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"
  ]
}

最佳答案

由于我无法使用react-router的Redirect来链接到/auth/login,所以我在方法中更改了window.location.href并返回了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>
    );
  }
}

关于reactjs - React-router如何重定向到服务器端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701988/

相关文章:

ruby-on-rails - Heroku 路线上带有 React 应用程序的 Rails 无法在刷新时工作

javascript - 为什么我不能在 react-router 4.x 中嵌套 Route 组件?

reactjs - React redux-beacon 跟踪链接点击分析

javascript - export `react-router` 从共享组件库重定向

javascript - TypeError : currentTodos. map 不是函数

javascript - React 组件无法读取未定义的属性

javascript - 流类型不适用于匿名函数内的外部作用域变量

javascript - 如何使用 Jest 0.8.x 测试像 react-router 2.0 中那样使用上下文的 React 组件

android - React Native 中 iOS 和 Android 的 UI 层是否会发生变化?

javascript - 使用 React、博客文章和 Wordpress API 进行动态路由