I use React, React-Router and Superagent. I need an authorization function in my web application. Now, if the token has expired, I need to redirect the page to the login page.
I put the ajax call function in a separate module, and a token will be sent for each request header. In one of my components, I need to get some data using an ajax call, as shown 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 I got error 401 (unauthorized), possibly because the token has expired or there are not enough privileges, the page should be redirected to the login page. Right now, in my api module, I have to use window.loication="#/login", I do not think this is a good 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));
},
response-router api. ? , .