首页 > 解决方案 > ReactJS + NodeJS:如果未登录,如何正确重定向用户?

问题描述

我有一个受保护的 URL - 如果他试图呈现他不允许的页面(这是在 ReactJS 组件中),这就是我重定向用户的方式:

render() {
  if(!this.props.auth.isAuthenticated) {
    this.props.history.push('/');
  }
  ...

当他没有登录时,他会被重定向到主页上。但是在控制台中,我得到了这两个错误:

index.js:2178 Warning: Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

该消息表明我可以将if-block 移动到componentWillMount? 然而,不是componentWillMount被弃用了吗?

和第二条错误消息:

xhr.js:178 GET http://localhost:3000/api/cars 401 (Unauthorized)

此消息是由 NodeJS 路由中的此代码块引起的:

router.get('/cars', passport.authenticate('jwt'), function(req, res, next) {
    if (req.isAuthenticated()) {
        console.log('logged in');

        Car.find({}).sort('name').exec(function(err, cars) {
            if(err) throw err;
            res.send(JSON.stringify(cars));
        });
    } else {
        // not logged in
        console.log('not logged in');
        //res.send(401);
    }
});

如果用户未通过身份验证,401则会在控制台中引发错误,并且不会执行此路由中的代码。这是正确的行为吗?为什么控制台中仍然有错误?

编辑: ReactJS 组件:

class Car extends Component {
    constructor() {
        super();
        this.state = {
            name: '',
            errors: {},
            cars: []
        }
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    UNSAFE_componentWillMount() {
        if(!this.props.auth.isAuthenticated) {
            this.props.history.push('/');
        }
    }

    componentDidMount() {
        //console.log('x');
        //console.log(this.props.auth);
        //let self = this;
        axios.get('/api/cars')
            .then((response) => {
                this.setState({cars: response.data});
            }).catch(err => {
                console.log('CAUGHT IT! -> ', err);
                if (err.response.status === 401) {
                    //this.props.history.push('/');
                }
                return err;
            })
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.auth.isAuthenticated) {
            this.props.history.push('/')
        }
        if(nextProps.errors) {
            this.setState({
                errors: nextProps.errors
            });
        }
    }

    handleInputChange(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    handleSubmit(e) {
        e.preventDefault();
        const car = {
            name: this.state.name
        }
        console.log(car);
        axios.post('/api/cars/create', car)
            .then(function(response) {
                console.log('response.data: ', response.data);
                if(response.data == "success"){
                    console.log('successssss');
                }
            }).catch(function(err) {
                console.log(err)
            });
    }


    render() { ...

标签: node.jsreactjspassport.js

解决方案


请不要在一个堆栈溢出问题中提出多个问题


错误一:

错误消息清楚地表明您不应该在 render 方法中导航到另一个页面。但你正在这样做。正如消息所示,您可以在 componentWillMount livecycle 方法中移动代码,但请注意,此检查不会在每次重新渲染时运行。

错误2:

您似乎正在调用此路由,该路由受身份验证保护,但未经身份验证。在没有看到您的客户端代码的情况下,我无法进一步评论。


推荐阅读