AngularJS网站因反向代理上的会话过期而出现错误。

huangapple go评论86阅读模式
英文:

AngularJS website errors because of session expired on reverse proxy

问题

我正在管理一个AngularJS网站,该网站位于一个用于身份验证的反向代理后面。
几个小时后,反向代理上的会话会过期。

如果网站仍然在浏览器中打开,并且用户点击页面,框架将返回包含非JavaScript内容的JavaScript,而是反向代理登录页面的HTML,以<!DOCTYPE html>开头。

这无法解析,并引发错误"Uncaught SyntaxError: expected expression, got '<'"
整个页面由于这些错误变黑。
一个临时解决办法是刷新页面,但是我们的所有用户都不知道这一点。

我该如何优雅地解决这个问题?

英文:

I'm managing an AngularJS website behind a reverse proxy used for authentication.
After a few hours, that session on the reverse proxy expires.

If the website is still open in a browser, and a user click on a page, the framework will return javascript which contains not javascript, but the HTML of the reverse proxy login page, starting with <!DOCTYPE html>

This can't be parsed and provoke an error "Uncaught SyntaxError: expected expression, got '<'"
The whole page is black because of these errors.
A workaround then is to refresh the page, but all of our users don't know it.

What can I do to fix the problem gracefully ?

答案1

得分: 0

使用AngularJS HTTP拦截器来检查API响应是否包含HTML。如果包含HTML,这意味着会话已过期,因此将用户重定向到登录页面或显示会话过期通知。

这是一个经典示例,但您需要根据您的代码进行调整:

app.factory('myInterceptor', function($q, $window) {
  return {
    response: function(response) {
      if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html')) {
        $window.location.href = '/login';
      }
      return response;
    }
  };
});

app.config(function($httpProvider) {
  $httpProvider.interceptors.push('myInterceptor');
});

希望我的回答对您有帮助。

英文:

Use an AngularJS HTTP interceptor to check if API responses contain HTML. If it does, it means the session has expired, so redirect the user to the login page or show a session expired notification.

Here's a classic example, but you'll need to adapt it to your code:

app.factory(&#39;myInterceptor&#39;, function($q, $window) {
  return {
    response: function(response) {
      if (typeof response.data === &#39;string&#39; &amp;&amp; response.data.includes(&#39;&lt;!DOCTYPE html&#39;)) {
        $window.location.href = &#39;/login&#39;;
      }
      return response;
    }
  };
});

app.config(function($httpProvider) {
  $httpProvider.interceptors.push(&#39;myInterceptor&#39;);
});

Hope my answer helps you

huangapple
  • 本文由 发表于 2023年7月13日 19:45:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定