Angular HTTP:状态 -1 和 CORS [英] Angular HTTP: Status -1 and CORS

查看:32
本文介绍了Angular HTTP:状态 -1 和 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的 Angular 应用程序中,有时我们会返回 http 状态 -1.状态 -1 发​​生在关闭的弹出窗口上,因此用户不受它的影响,只会影响我们的日志.

我试图通过这样做来处理它

 开关 (response.status) {案例0:休息;情况1:休息;案例401:localStorageService.clearAll();redirectToUrlAfterLogin.url = $location.path();$location.path('/登录');

在 或 Fetch - 降低跨源 HTTP 请求的风险.

请参阅使用 CORS 允许跨域访问.

In our angular application sometimes we get http status -1 returned to us. The status -1 happens on a popup that is closed, so the user isn't affected by it, just our logs.

I attempted to handle it by doing

      switch (response.status) {
        case 0:
          break;
        case -1:
          break;
        case 401:
          localStorageService.clearAll();
          redirectToUrlAfterLogin.url = $location.path();
          $location.path('/login');

Which was suggested in AngularJS Issue #12920

We are definitely getting less logs in, but there are still some HTTP -1 status codes. Is there a different way I should be handling the -1?

解决方案

In my experience, the most common cause of status of a -1, is that the browser blocked the response because of a violation of Same Origin Policy.

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow cross-domain requests.

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers. Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.

See Use CORS to allow cross-origin access.

这篇关于Angular HTTP:状态 -1 和 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆