React无React Router时后端重定向登录失效问题求助
问题分析与解决方案
核心问题在于:axios发送的是AJAX异步请求,后端返回的重定向响应会被axios内部处理,不会触发浏览器的页面跳转。而直接在新标签页打开URL是浏览器发起的普通HTTP请求,浏览器会自动遵循重定向完成页面导航。
针对你的场景,有两种可行的解决方式:
方式一:后端返回跳转URL,前端手动触发页面导航
修改Rails后端逻辑,不要直接返回重定向响应,而是返回包含目标token端点URL的JSON数据。例如后端返回:
{ "redirect_url": "/path/to/token" }
然后在前端axios的then回调里,手动让浏览器跳转:
this.submit = (event) => { event.preventDefault(); // 保留此代码,阻止表单默认提交行为 this.setState({ inlineNotificationError: null }); const formData = { login: this.model.login, password: this.model.password }; const params = this.props.loginData.loginPathRequestParams const combinedParams = { ...formData, ...params }; axios.post(this.props.loginData.loginPathUrl, combinedParams, { headers: { 'Content-Type': 'application/json' } }) .then(response => { // 手动跳转到后端返回的URL window.location.href = response.data.redirect_url; }) .catch(error => { this.setState({ inlineNotificationError: { title: error.response.data.error }}); }) .finally(() => { this.model.login = ''; this.model.password = ''; }); };
方式二:放弃axios,使用原生表单提交
既然你没有使用React Router,且需求是让浏览器处理重定向,可以直接利用原生HTML表单的提交行为,不需要AJAX请求:
this.submit = (event) => { // 移除event.preventDefault(),让表单默认提交 this.setState({ inlineNotificationError: null }); };
同时确保你的表单元素设置了正确的action和method属性:
<form action={this.props.loginData.loginPathUrl} method="POST"> <!-- 用户名输入框 --> <input type="text" name="login" value={this.model.login} onChange={/* 你的输入处理逻辑 */} /> <!-- 密码输入框 --> <input type="password" name="password" value={this.model.password} onChange={/* 你的输入处理逻辑 */} /> <button type="submit">登录</button> </form>
补充说明
你当前的代码中,axios接收了后端的重定向响应,但只是打印了response却没有做任何页面跳转操作,所以浏览器停留在当前登录页。而直接在新标签打开URL时,是浏览器发起的普通请求,会自动跟进重定向完成登录页面的跳转。
内容的提问来源于stack exchange,提问作者pei wei
相关产品推荐
相关产品推荐

