Angular HTTP: Status -1 and CORS

怎甘沉沦 提交于 2019-11-27 07:54:22

问题


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?


回答1:


When the request is aborted or timed-out, the request lands as an error with status -1.

Taken from the official docs:

Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout.

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.




回答2:


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.



来源:https://stackoverflow.com/questions/35418688/angular-http-status-1-and-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!