【问题标题】:unintended redirect with react router使用反应路由器的意外重定向
【发布时间】:2017-03-31 20:38:53
【问题描述】:

我有一个简单的 react 应用程序,它带有这样设置的 react 路由器。它位于我应用的根目录 (/)

import React, {Component} from 'react';
import { render } from 'react-dom'
import { Router, Route, hashHistory, IndexRoute } from 'react-router'

import Main from "./components/main";
import Index from "./components/polls/index";
import New from "./components/polls/new";
import Show from "./components/polls/show";
import PollAdmin from "./components/polls/poll_admin"

render((
  <Router history={hashHistory}>
    <Route path="/" component={Main}>
      <IndexRoute component={Index}/>
      // more components here, removed for brevity
    </Route>

  </Router>
), document.getElementById('app'))

当用户登录(不是路由器的一部分)时,他们会被重定向回/。 一旦他们这样做了,Index 组件就会响应(见下文)。 然后浏览器访问/api/polls,这不是预期的。 /api/polls 是一个 api 端点,用于获取要显示的数据。 我通过删除componentDidMount 函数确认了这一点。该功能消失后,浏览器不会访问 /api/polls

为什么浏览器访问/api/polls而不是发出异步请求?如何正确重定向回/

import React, {Component} from 'react';
import { Link } from 'react-router';
import axios from 'axios';

class Index extends React.Component {

  constructor(props){

    super(props);
    this.state = {
      polls: []
    }
  }

  componentDidMount() {
    var _this = this;

      axios('/api/polls')
        .then(function(result){
          _this.setState({
            polls: result.data.polls
          })
        })
        .catch(function(err){
        })

  }

  ...
  }

}

export default Index;

【问题讨论】:

  • 你调试了吗?重定向实际上发生在哪里?什么 LOC 导致它?

标签: javascript reactjs react-router


【解决方案1】:

经过一番摸索,我解决了这个问题。首次访问/ 时,组件Index/api/polls 发出异步请求。然后用户通过 Twitter 登录。以下是相关路线:

router.get('/auth/twitter', passport.authenticate('twitter'));
router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

问题在于req.session.returnTo/api/polls 存储为最后一个“访问”的网址。登录后浏览器重定向到/api/polls 在页面上呈现一些丑陋的json。出于我的目的,这是一个简单的解决方法。我只是将路线更改为:

router.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect('/');
});

用户总是被重定向回/,这正是我想要的。如果您想重定向回用户的最后一页,我不确定该怎么做。

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2017-07-21
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2020-10-22
    • 2018-08-13
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多