嗨,我正在使用 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/