Angular: $http requests gives -1 status

Deadly 提交于 2019-12-05 09:27:13

Thanks a lot, @Sebastian Sebald and @Dex for guiding me to the solution. I just wanted to run a simple Node.js server on my computer serving messages to my (simple) Angular script.

Yes, it was a cross-domain issue. @TonyTakeshi gave a good solution to this issue. You can solve it in the node.js server file via:

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

Heavy stuff for a simple test configuration ;-)

Please consult the official Angular docs for $http. It states the following:

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

So I guess it is a problem with your backend. Maybe take a look in the developer console to check if the request reaches your server.

If you're talking to Tomcat and using a Filter which sets e.g. a 401 for restricted access, this filter may prevent your Access-Control headers from being sent along with the request, and your 401 will show up in Angular as a -1, even though it's clearly a 401 in the in-browser network requests log .

Just posting this here for when I forget and re-do the same dumb thing in a year.

Another suggestion as I recently encountered this issue:

It was intermittent, not reproducible and would occur in shifting time intervals, sometimes after ~20 seconds, sometimes in >5ms (not enough time for a full round trip)

Things I isolated while testing: Server, load balancer, firewall, angularjs application itself, browser.

Extensive testing exonerated all culprits and it was not a CORS issue. The problem was the end users' feeble, intermittent internet connection. Implementing an HTTP interceptor retry function if the status came back -1 and a max retry count effectively handled the issue.

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