Angularjs long polling - javascript

I am trying to perform a simple long poll request in Angularjs - I make a GET request and it hangs on till the server responds. Then I make the request again and wait for the next response - and so on.
However, for some reason the code is quite unreliable and misses around 80% of the responses sent from the server.
Below is my code:
main.messages=[];
...
main.poll=function(){
$http.get('http://localhost:8080/message')
.success(function(data){
console.log(data);
main.messages.push(data);
main.poll();
})
.error(...)
};
Is there something obvious that I am missing here?
The server can detect that the browser is connected, and the server does send a response but the code above does not get the response (no console output and no error). I tried making this request with postman (chrome extension) and the long-poll worked perfectly there so I think the problem is somewhere in here.
update: the problem occurs only on Google Chrome and only when there is more than one tab performing the long-poll simultaneously. There is some seemingly random behaviour on creating and closing new tabs with the long-poll.

I found out what was causing this. Chrome will only longpoll a given url one tab at a time. If a user has got multiple tabs open requesting the same longpoll, Chrome waits for the longpoll in the first tab to finish before starting the poll in the second tab.
I think that the browser looks at the long-poll request as a 'server that is not responding'. When you try to make the same request in a new tab, the browser does not actually make that same request again to conserve resources. If you look at the network tab, it will show a pending request. But that's a 'lie', the browser is actually waiting for the server to respond for the first tab's request. Once it gets a response from the server for the first tab's request, only then will it query the server for the second tab's request.
In other words, the browser (Chrome and Opera) will not normally make two long-poll requests to the same endpoint simultaneously - even if these requests are coming from two different tabs.
However, sometimes after a certain amount of time it decides to release request for the second tab as well. But I was not able to figure out any rule for this. If you have 3 tabs open with the same request, closing the first causes 2 simultaneous requests from the remaining two tabs. But if you have 6 tabs open, closing the first causes only 3 simultaneous requests and not 5. I'm sure there would be some rules governing this behaviour but I guess we have to write code assuming that the requests may or may not take place simultaneously and the browser may wait for one request to finish before working on the second.
Safari does not have this behaviour - it will make multiple requests via multiple tabs simultaneously. But Chrome and Opera do show this behaviour.
So rather than 'broadcasting' data simultaneously to all connected clients, I am now changing my code to use timestamps to figure out how much data a client needs and then send that data.

Related

NS_BINDING_ABORTED only on first PUT attempt in Firefox

In my JS single page web app I have a reset-button that triggers 'onclick' and will use vanilla fetch() to PUT an empty JSON array to my API. Both are hosted on the same domain/server. When using Firefox (currently 86.0), the first time I push the reset button, the call is aborted. The console says NetworkError when attempting to fetch resource white the Network tab says NS_BINDING_ABORTED in the transferred column.
When I reload my app (F5) and push the same button again, it works. And also any time from now on. As the same code is executed, the failing and the working calls would send the same headers and payload.
Chrome does not show this behavior, there the first call works too.
Even stranger, this first failing PUT call in Firefox seems to only fail once per URL. The web app provides "areas" to users with the area ID in the frontend URL, e.g.
https://example.org/areas/#/myAreaA
and
https://example.org/areas/#/myAreaB
These will PUT to the API, which also has these IDs in their URLs:
https://example.org/api/areas/myAreaA/state/
and
https://example.org/api/areas/myAreaB/state/
For each of these URLs, the first PUT call fails with NS_BINDING_ABORTED but works thereafter. If I copy the URL for such an area into a new Tab or even close+open the Browser again, the Error does not appear again. The web app does not use any cookies.
The web app does a lot of other API calls to the same backend/areaID, no other show this behavior. However, this is the only PUT call, all other calls are GET/POST/HEAD/PATCH requests.
What could be the reason for the first PUT failing?
Following "NetworkError when attempting to fetch resource." only on Firefox I found the problem. It seems that Firefox' onclick event propagation interferes here with the fetch() call. As soon as I added
event.preventDefault()
in the onclick-handler before doing the actual fetch(), everything started to work again.

Cancel ajax request from chrome developer tools

I want to cancel the ajax request from chrome developer tools after it has initiated. For example I want to test my fallback message is showing correctly. I can set No throttling to Offline so that all calls will fail, but I just want to test one API to fail, for debugging purposes.
I know I can use abort() methods, (ie I can do it through JavaScript). I dont want to touch the code for just this need.
There's a replay XHR option in right click of the API, It'll be great there is something like abort XHR in same way. But there isn't.
From Chrome 59 you can block specific requests from Network tab of developer tools itself.
https://developers.google.com/web/updates/2017/04/devtools-release-notes#block-requests
Right-click on the request in the Network panel and select Block Request URL. A new Request blocking tab pops up in the Drawer, which lets you manage blocked requests.
So, In my case, I will run the code block that specific API and then re-run. :)
As per the comment, this is not exactly canceling the already started request, but checking how the app behaves if only one request is failed by blocking only one request. Thanks #Ross Ivantsiv for this.
There is a simple trick I use. Pressing F5 while in the tab immediately followed by ESC.
XHR requests still active by chrome are canceled before the new answer is loaded.
If you don't know the exact URL, You can debug all XHR by adding an XHR breakpoint within the Sources tab
Or if you know the name or part of XHR URL which you need to debug you can add it XHR by clicking the ( + ) icon.

SoundCloud Api redirect confusion and Audio Api Streams

I am attempting to make a request to the SoundCloud API. Then when I get the response I set the stream_url as the source of an < audio > element.
This works:
http://matthiasdv.org/beta/
But not always... When you search for 'Bonobo' for example, you can play the first few tracks without any issue. But when you try to play 'London Grammar - Hey Now (Bonobo remix)' - the 7th result - it won't play. It throws no errors whatsoever.
I've been tinkering around with Chrome's webdev-tools and under the network tab I see the requests being made. I found that tracks that DO play have a short Request Url, like this:
https://ec-media.sndcdn.com/vR5ukuOzyLbw.128.mp3?f10880d39085a94a0418a7ef69b03d522cd6dfee9399eeb9a522029f6bfab939b9ae57af14bba24e44e1542924c205ad28a52352010cd0e7dd461e9243ab54dc0f0bba897d
And the ones that don't look like this:
https://cf-media.sndcdn.com/8PCswwlkswOd.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vOFBDc3d3bGtzd09kLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MzM0Mjc2MDN9fX1dfQ__&Signature=cD-XVhnvQnIATkfrBDDVy0Q7996C8DymwxRLwBBduab0~L0MynF1ftcMky~21T8Q-gCZ2~dMK8dz7uVxvJTIJgXPxEZvhNtbvescMK6iFMg-xSAty-4OhJYjrIZJ2j8NE4uNA4Ml7MWbWcQw4KtUtpZitOQuguS3DPFDII3VF-dvzb2L~xG-G8Uu3uOnI1WhnAAfhf1QWMO7swwB89HtcCiuVBmfluG28ELrJEq-au8mqIMB3sLTno6nUuTtpHXR2ayXBsYcYLLJVXa3Ul8p1rhLS5XWHKWXY8xug4jwey27~C5PVAomK6Z5lJx-mz-0zYs4riUYtl0zACbZ1OfwTQ__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ
Now at first glance I figured it was an encoding issue, but wrapping a quick encodeURI() around the ajax url did not work.
Furthermore I do not understand where these urls come from. In my code I am directing my ajax request towards, for example:
https://api.soundcloud.com/tracks/140326936/stream?client_id=5c6ceaa17461a1c79d503b345a26a54e
Thus, the request url in the GET request (as found under 'network' in Chrome's webdev tools) makes no sense to me. Is SoundCloud redirecting get requests to a CDN-host? One more thing I've noticed is that each time TWO requests are fired instead of one. The first one is always canceled and contains a 'Provisional headers are shown' warning. I believe this is because I am setting crossOrigin = "anonymous", otherwise certain browsers would not load the content.
What I guess may cause the problem is that when the url is set as the src attribute of the element an evenListener is fired in the dancer.js library, which handles the Audio Api and the playback (https://github.com/jsantell/dancer.js/). It may be that encodeURI() is required somewhere in the library.
I decided to ask the question anyhow because I don't understand how the Request Urls's above are formed and why two, instead of one, requests are being fired and why the first is always cancelled.
Any hints which my solve the playback issue are more than welcome too...
When you run the request for
https://api.soundcloud.com/tracks/140326936/stream?client_id=5c6ceaa17461a1c79d503b345a26a54e
you get a HTTP 302 Found response from the server, which is a URL redirect (http://en.wikipedia.org/wiki/HTTP_302). This will cause your browser to load from the new URL that the server returns, and thus the two requests you see. The server basically says "yeah, I know where to find that file, ask that guy over there".
The reason why one works and the other not, I'd think, is that https://ec-media.sndcdn.com has the Access-Control headers set while https://cf-media.sndcdn.com doesn't. This is an issue with the server configuration and unfortunately nothing you can control from the client side. Dunno if it's a deliberate move by soundcloud or if it's something you could ask them about.

Determine source of API request?

I have been introduced to a web application that I need to make some modifications to.
The app is huge, and there are perhaps 100 Javascript files. These files send requests to a third party API all the time.
Now, in the console, I can see all these requests. Let's say that one looks like:
GET http://123.456.789.10:8000/v1/accounts/accountnum/children?_=1422026843600
Then of course I can see the parameters sent, headers and response. My problem is that I need to locate the JS file which is sending one particular request. Searching all the files for the API target URL reveals that 40 or 50 files send requests to this same URL, with similar parameters.
Is there a way I can find out the source file of one specific request? Something like sent from filename.js on line 123 would be ideal, but just the file name would be of great help too.
I could go through all the files and try each one individually, but that seems like a huge waste of time. There would be A LOT of code to go through.
If you know what to do in the application to make the request occur, in Chrome you can use an XHR breakpoint to catch it:
Navigate to the point where you're about to do the thing that causes the request
Open Dev Tools
Switch to the Sources tab
On the right, scroll down to "XHR Breakpoints"
Click the + button, fill in some appropriate subset of the URL (or leave it blank to break on all XHR)
Add it
Do the thing that does the request
Chrome will break and take you to the line of code that was triggering the XHR.

How to make auto-updating (ajax) counter correctly? Or how to disable network log?

I'm trying to make auto-reload counter (for ex.: Messages [num]).
So, I just in setTimeout(); getting JSON code from test_ajax.php. I think it's not correctly..
Can I send info by server (I think not, but suddenly I something don't know..)?
Why I think that's not correctly: because when I'm looking in my chrome network log (F12 -> network tab), I see a lot of requests (to test_ajax.php), but when, I'm visiting vk.com (great example for ajax) or facebook.com, I don't see any requests while something will not change.
So, what's incorrectly in my solution (or what's bad..)?
UPD: Sorry, vk.com sending requests to q%NUM%.queue.vk.com every 25s, but until 25s last request's status is "Pending". When someone, for example, sending me a message it immediately display it. And request has parameter "wait" which equals 25. This delay in requests doing on server side.. But how?
Ajax counter can be done in easy just include below files
index.html
counter.php (ajax file)
necessary images
JS file (for jquery paging call)
download link: https://docs.google.com/open?id=0B5dn0M5-kgfDcE0tOVBPMkg2bHc
What you are looking for is called COMET (also sometimes called Reverse AJAX) techniques.
Doing what you want to do, e.g. regular polls, is one way of doing it.
A lot is actually happening on the server side; to avoid recreating new connections on every poll, some servlet containers like Jetty started to implement techniques like Continuation which basically maintain a two-way connection open.
In the Java world, with Servlet 3, you have asynchronous calls as part of the specs.

Categories