Update:
examples works fine, sorry, my bad. Assuming there’s somebody who is listening 8888 port on the localhost. The code below works bad on iOS/mac os:
std::string m_address = "127.0.0.1"; int m_port = 8888; asio::io_service m_service; asio::ip::tcp::socket m_socket(m_service); asio::ip::tcp::endpoint ep(asio::ip::address::from_string(m_address), m_port); m_socket.async_connect(ep, [] (const asio::error_code& err) { std::cout << "onConnect -> " << err.message() << std::endl; }); m_service.run();
Output on a Debian:
Output on a Mac OS:
onConnect -> Undefined error: 0
What does it mean when JavaScript network calls such as fetch or XMLHttpRequest, or any other type of HTTP network request, fail with an HTTP status code of 0?
This doesn’t seem to be a valid HTTP status code as other codes are three digits in HTTP specification.
I tried unplugging the network completely as a test. It may be unrelated, but that resulted in status code 17003 (IIRC), which cursory searching suggests means «DNS server lookup failed».
The same code works fine from some locations and systems, however within certain environments it fails with status code 0 and there is no responseText provided.
This is a typical HTTP POST to an Internet URL. It does not involve file:// which I understand may return 0 indicating success in Firefox.
whitneyland
10.6k9 gold badges60 silver badges67 bronze badges
asked May 16, 2009 at 11:11
mike nelsonmike nelson
20.9k14 gold badges65 silver badges74 bronze badges
5
Many of the answers here are wrong. It seems people figure out what was causing status==0 in their particular case and then generalize that as the answer.
Practically speaking, status==0 for a failed XmlHttpRequest should be considered an undefined error.
The actual W3C spec defines the conditions for which zero is returned here:
https://fetch.spec.whatwg.org/#concept-network-error
As you can see from the spec (fetch or XmlHttpRequest) this code could be the result of an error that happened even before the server is contacted.
Some of the common situations that produce this status code are reflected in the other answers but it could be any or none of these problems:
- Illegal cross origin request (see CORS)
- Firewall block or filtering
- The request itself was cancelled in code
- An installed browser extension is mucking things up
What would be helpful would be for browsers to provide detailed error reporting for more of these status==0 scenarios. Indeed, sometimes status==0 will accompany a helpful console message, but in others there is no other information.
answered Jan 24, 2013 at 17:56
10
I believe the error code indicates that the response was empty, (as not even headers were returned). This means the connection was accepted and then closed gracefully (TCP FIN).
There are a number of things which could cause this, but based off of your description, some form of firewall seems the most likely culprit.
answered May 25, 2009 at 8:32
NickNick
1,77913 silver badges13 bronze badges
3
For what it is worth, depending on the browser, jQuery-based AJAX calls will call your success callback with a HTTP status code of 0. We’ve found a status code of «0» usually means the user navigated to a different page before the AJAX call completed.
Not the same technology stack as you are using, but hopefully useful to somebody.
answered Oct 18, 2010 at 16:52
Cory R. KingCory R. King
2,7461 gold badge24 silver badges22 bronze badges
5
wininet.dll
returns both standard and non-standard status codes that are listed below.
401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed
12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception
For the status code «zero» are you trying to do a request on a local webpage running on a webserver or without a webserver?
XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.
answered May 25, 2009 at 7:33
Christophe EbléChristophe Eblé
8,0413 gold badges33 silver badges32 bronze badges
1
An HTTP response code of 0 indicates that the AJAX request was cancelled.
This can happen either from a timeout, XHR abortion or a firewall stomping on the request. A timeout is common, it means the request failed to execute within a specified time. An XHR Abortion is very simple to do… you can actually call .abort() on an XMLHttpRequest object to cancel the AJAX call. (This is good practice for a single page application if you don’t want AJAX calls returning and attempting to reference objects that have been destroyed.) As mentioned in the marked answer, a firewall would also be capable of cancelling the request and trigger this 0 response.
XHR Abort: Abort Ajax requests using jQuery
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
It’s worth noting that running the .abort() method on an XHR object will also fire the error callback. If you’re doing any kind of error handling that parses these objects, you’ll quickly notice that an aborted XHR and a timeout XHR are identical, but with jQuery the textStatus that is passed to the error callback will be «abort» when aborted and «timeout» with a timeout occurs. If you’re using Zepto (very very similar to jQuery) the errorType will be «error» when aborted and «timeout» when a timeout occurs.
jQuery: error(jqXHR, textStatus, errorThrown);
Zepto: error(xhr, errorType, error);
answered Sep 13, 2012 at 17:45
Cory DanielsonCory Danielson
14.2k3 gold badges44 silver badges51 bronze badges
Workaround: what we ended up doing
We figured it was to do with firewall issues, and so we came up with a workaround that did the trick. If anyone has this same issue, here’s what we did:
-
We still write the data to a text file on the local hard disk as we previously did, using an HTA.
-
When the user clicks «send data back to server», the HTA reads in the data and writes out an HTML page that includes that data as an XML data island (actually using a SCRIPT LANGUAGE=XML script block).
-
The HTA launches a link to the HTML page in the browser.
-
The HTML page now contains the javascript that posts the data to the server (using Microsoft.XMLHTTP).
Hope this helps anyone with a similar requirement. In this case it was a Flash game used on a laptop at tradeshows. We never had access to the laptop and could only email it to the client as this tradeshow was happening in another country.
answered May 26, 2009 at 21:29
mike nelsonmike nelson
20.9k14 gold badges65 silver badges74 bronze badges
1
As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.
To test this you can do either of the following:
1) Use this chrome extension, Requestly to redirect your url from the https
version of your url to the http
version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don’t have to change your app at all, and you can simply «rewrite» your url using this extension.
2) Change the code of your app to optionally make your endpoint redirect to the http
version of your url instead of the https
version (or vice versa). If you do this, the request will fail with status code 0.
answered Aug 3, 2016 at 18:05
Brad ParksBrad Parks
65.8k63 gold badges255 silver badges332 bronze badges
2
In my case the status became 0 when i would forget to put the WWW in front of my domain. Because all my ajax requests were hardcoded http:/WWW.mydomain.com and the webpage loaded would just be http://mydomain.com it became a security issue because its a different domain. I ended up doing a redirect in my .htaccess file to always put www in front.
answered Aug 5, 2013 at 11:05
I found a new and undocumented reason for status == 0. Here is what I had:
XMLHttpRequest.status === 0
XMLHttpRequest.readyState === 0
XMLHttpRequest.responseText === ''
XMLHttpRequest.state() === 'rejected'
It was not cross-origin, network, or due to cancelled requests (by code or by user navigation). Nothing in the developer console or network log.
I could find very little documentation on state() (Mozilla does not list it, W3C does) and none of it mentioned «rejected».
Turns out it was my ad blocker (uBlock Origin on Firefox).
answered Oct 18, 2017 at 15:27
Jonathan AmendJonathan Amend
12.7k3 gold badges22 silver badges29 bronze badges
In my case, it was because the AJAX call was being blocked by the browser because of the same-origin policy. It was the least expected thing, because all my HTMLs and scripts where being served from 127.0.0.1
. How could they be considered as having different origins?
Anyway, the root cause was an innocent-looking <base>
tag:
<base href='<%=request.getScheme()%>://<%=request.getServerName() + ":" + request.getServerPort() + request.getContextPath()%>/'/>
I removed the <base>
tag, which I did not need by the way, and now it works fine!
answered Jan 27, 2013 at 17:48
SaintaliSaintali
4,4322 gold badges28 silver badges49 bronze badges
In addition to Lee’s answer, you may find more information about the real cause by switching to synchronous requests, as you’ll get also an exception :
function request(url) {
var request = new XMLHttpRequest();
try {
request.open('GET', url, false);
request.send(null);
} catch (e) {
console.log(url + ': ' + e);
}
}
For example :
NetworkError: A network error occurred.
answered Mar 30, 2018 at 11:07
McXMcX
1,2962 gold badges12 silver badges16 bronze badges
In case anyone else comes across this problem, this was giving me issues due to the AJAX request and a normal form request being sent. I solved it with the following line:
<form onsubmit="submitfunc(); return false;">
The key there is the return false, which causes the form not to send. You could also just return false from inside of submitfunc(), but I find explicitly writing it to be clearer.
answered Sep 7, 2012 at 20:36
samozsamoz
56.5k55 gold badges141 silver badges195 bronze badges
1
It should be noted that an ajax file upload exceeding the client_max_body_size
directive for nginx will return this error code.
answered Aug 10, 2015 at 16:40
r3wtr3wt
4,6332 gold badges33 silver badges55 bronze badges
If you are testing on local PC, it won’t work. To test Ajax example you need to place the HTML files on a web server.
answered Aug 15, 2019 at 21:37
In my case, the error occurred in a page requested with HTTP protocol, with a Javascript inside it trying to make an HTTPS request. And vice-versa.
After page loading, press F12 (or Ctrl + U) and take a look at the HTML code of your page. If you see something like that in your code:
<!-- javascript request inside the page -->
<script>
var ajaxurl = "https://example.com/wp-admin/admin-ajax.php";
(...)
</script>
And your page was requested this way:
http://example.com/example-page/2019/09/13/my-post/#elf_l1_Lw
You certainly will face this error.
To fix it, set the protocol of the Javascript request equal to the protocol of page request.
This situation involving different protocols, for page and js requests, was mentioned before in the answer of Brad Parks but, I guess the diagnostic technique presented here is easier, for the majority of users.
answered Sep 16, 2019 at 17:47
Oct 16, 2019 10:05 AM in response to -the_fixer-
Hi Eddie,
In Terminal cd is used to change directory…
Moving around
When you’re in the Finder and you want to move to another folder, you find that folder and double-click it. From the command line, you use the cd (or change directory) command instead. So let’s say you’re in your Home folder and want to peek inside the Downloads folder. To do that, you’d type cd Downloads. (Remember to always type a space after any command that has an additional argument, such as the name of a directory in the previous example.) Once you’ve done that, ls will show you the contents of your Downloads folder.
Here are a couple of quick tricks for moving around in your Mac’s file system.
If you type cd and press the Return key—with no directory specified—you’ll go back to your Home folder. (You can also type cd ~ to go there.)
If you type cd /, you’ll go to the root level of your startup disk.
If you type cd .. (that’s two periods), you’ll go to the directory above the one you’re currently in. So if you’re in your home folder, and type cd .., you’ll go to your Mac’s /Users folder.
And if you type cd — (hyphen) you’ll go back to the directory you were in before the last time you issued the cd command.
That should be enough to get you started. Try playing around in Terminal, exploring your folders and files with just those two commands. In future articles, I’ll show you how you can apply the ls and cd commands in more depth, so you can be comfortable flitting around your file system from the command line.
Note: When you purchase something after clicking links in our articles, we may earn a small commission. Read our affiliate link policy for more details.
https://www.macworld.com/article/2042378/master-the-command-line-navigating-files-and-folders.html
Код ответа HTTP 0 указывает, что запрос AJAX был отменен.
Это может произойти либо от тайм-аута, либо от прерывания XHR, либо от брандмауэра, топающего по запросу. Тайм-аут является общим, это означает, что запрос не выполнен в течение указанного времени. Аборт XHR очень прост в использовании… вы можете фактически вызвать .abort() в объекте XMLHttpRequest, чтобы отменить вызов AJAX. (Это хорошая практика для одностраничного приложения, если вы не хотите, чтобы AJAX-вызовы возвращались и пытались ссылаться на объекты, которые были уничтожены.) Как упоминалось в отмеченном ответе, брандмауэр также мог бы отменить запрос и запустить его 0.
XHR Abort: Отменить запросы Ajax с использованием jQuery
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
Стоит отметить, что запуск метода .abort() объекта XHR также приведет к обратному вызову ошибки. Если вы выполняете какую-либо обработку ошибок, которая анализирует эти объекты, вы быстро заметите, что прерванный XHR и XHR с тайм-аутом идентичны, но с jQuery textStatus, который передается в обратный вызов ошибки, будет «отменен» при прерванном и «таймаут» с таймаутом. Если вы используете Zepto (очень похожий на jQuery), errorType будет «ошибкой» при прерывании и «таймаутом», когда произойдет таймаут.
jQuery: error(jqXHR, textStatus, errorThrown);
Zepto: error(xhr, errorType, error);
For solving this problem, we can create the same SystemConfiguration «service» strucures manually using the scutil command:
First we create the IPv4 part of the service:
sam@shiny ~> sudo scutil
> d.init
> d.add Addresses * 10.75.131.2
> d.add DestAddresses * 10.75.131.2
> d.add InterfaceName utun1
> set State:/Network/Service/my_ipv6_tunnel_service/IPv4
> set Setup:/Network/Service/my_ipv6_tunnel_service/IPv4
And then we create the IPv6 part:
> d.init
> d.add Addresses * fe80::a65e:60ff:fee1:b1bf 2600:3c03::de:d002
> d.add DestAddresses * ::ffff:ffff:ffff:ffff:0:0 ::
> d.add Flags * 0 0
> d.add InterfaceName utun1
> d.add PrefixLength * 64 116
> set State:/Network/Service/my_ipv6_tunnel_service/IPv6
> set Setup:/Network/Service/my_ipv6_tunnel_service/IPv6
> quit
Once this is done, the output of scutil —dns (again modulo mdns stuff) changes:
DNS configuration
resolver #1
search domain[0] : home.munkynet.org
nameserver[0] : 10.20.4.4
if_index : 14 (en3)
flags : Request A records, Request AAAA records
reach : 0x00020002 (Reachable,Directly Reachable Address)
DNS configuration (for scoped queries)
resolver #1
search domain[0] : home.munkynet.org
nameserver[0] : 10.20.4.4
if_index : 14 (en3)
flags : Scoped, Request A records
reach : 0x00020002 (Reachable,Directly Reachable Address)
For full information about this problem, you can proceed to original answer.