reactjs - How redirect to login page when got 401 error from ajax call in React-Router? -
i using react, react-router , superagent. need authorization feature in web application. now, if token expired, need page redirect login page.
i have put ajax call functionality in separated module , token send on each request's header. in 1 of component, need fetch data via ajax call, below.
componentdidmount: function() { api.getone(this.props.params.id, function(err, data) { if (err) { this.seterrormessage('system error!'); } else if (this.ismounted()) { this.setstate({ user: data }); } }.bind(this)); },
if got 401 (unauthorized) error, maybe caused token expired or no enough privilege, page should redirected login page. right now, in api module, have use window.loication="#/login"
don't think idea.
var endcallback = function(cb, err, res) { if (err && err.status == 401) { return window.location('#/login'); } if (res) { cb(err, res.body); } else { cb(err); } }; get: function(cb) { request .get(base_url + resources) .end(endcallback.bind(null, cb)); },
but, can't easily, call react-router method in api module. there elegant way implemented easy feature? don't want add error callback in every react components need authorized.
i try this:
- use component's context manipulate router (
this.context.router.transitionto()
). - pass method api callout param.
// component.js ,contexttypes: { router: react.proptypes.func }, componentdidmount: function() { api.getone(this.props.params.id, this.context.router, function(err, data) { if (err) { this.seterrormessage('system error!'); } else if (this.ismounted()) { this.setstate({ user: data }); } }.bind(this)); }, // api.js var endcallback = function(cb, router, err, res) { if (err && err.status == 401) { return router.transitionto('login'); } if (res) { cb(err, res.body); } else { cb(err); } }; get: function(cb, router) { request .get(base_url + resources) .end(endcallback.bind(null, cb, router)); },
i know didn't want callback on each authenticated component, don't think there's special react-router shortcuts transition outside of router.
the other thing think of spin brand new router on error , manually send login route. don't think work since it's outside of initial render method.
Comments
Post a Comment