consuming a Rest-API with javascript in the browser - javascript

I'm writing a sever application in go providing a Rest-API. If the server gets a GET without JSON-content-type header it serves an empty html-page having a javascript module in its head. This javascript code uses fetch to consume the Rest-API and populates then according the document.body with content fetched from the server. Each "link" in the content triggers further calls to the API and corresponding updates to the content.
So far so good. But I made two irritating observations.
(obviously) the "back" and "forward" buttons of the browser stay inactive. Which seems logical since there are no loaded URLs associated with the content changes.
If I come to my Rest-UI from an other page and hit the browser's back-button I get as expected the other page back but if I hit now the browser's forward-button I see the JSON-response from my initial fetch instead of my Rest-UI content. Reloading my page makes it all good again but I can't offer that behavior to any user :)
Are there common approaches to deal with this behavior? E.g. removing the browser controls completely, feeding the browser-history "by hand" with js-callbacks, caching directives, ... (I'm inexperienced with js)

The root of the problem is that I overloaded the response of a GET request on the server-side: if the GET-request accepts JSON the server returns JSON otherwise it returns a html-page with the javascript which consumes the JSON. I. e. the javascript fetch for the JSON is the last GET-response for a given URL and goes as such into the browser's cache associated with that URL. A solution to that problem which works for me is to send a header with the JSON response turning of caching and signalling the browser with the "Vary"-header that the response depends on the "Accept"-header. An other solution might be to add distinct endpoints to the server for the Rest-requests.

Related

dynamically generate content for a page when clicking on product

everyone. I am making a website with t-shirts. I dynamically generate preview cards for products using a JSON file but I also need to generate content for an HTML file when clicking on the card. So, when I click on it, a new HTML page opens like product.html?product_id=id. I do not understand how to check for id or this part ?prodcut_id=id, and based on id it generates content for the page. Can anyone please link some guides or good solutions, I don't understand anything :(.
It sounds like you want the user's browser to ask the server to load a particular page based on the value of a variable called product_id.
The way a browser talks to a server is an HTTP Request, about which you can learn all the basics on javascipt.info and/or MDN.
The ?product_id=id is called the 'query' part of the URL, about which you can learn more on MDN and Wikipedia.
A request that gets a page with this kind of URL from the server is usually a GET request, which is simpler and requires less security than the more common and versatile POST request type.
You may notice some of the resources talking about AJAX requests (which are used to update part of the current page without reloading the whole thing), but you won't need to worry about this since you're just trying to have the browser navigate to a new page.
Your server needs to have some code to handle any such requests, basically saying:
"If anybody sends an HTTP GET request here, look at the value of the product_id variable and compare it to my available HTML files. If there's a match, send a response with the matching file, and if there's no match, send a page that says 'Error 404'."
That's the quick overview anyway. The resources will tell you much more about the details.
There are some solutions, how you can get the parameters from the url:
Get ID from URL with jQuery
It would also makes sense to understand what is a REST Api and how to build a own one, because i think you dont have a backend at the moment.
Here some refs:
https://www.conceptatech.com/blog/difference-front-end-back-end-development
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm

Node.js form update with and without ajax

What would be the "best" approach to dealing with forms which have to work without and with JavaScript enabled?
Would it be better to create different routes for each, like
AJAX request: route "API/contact" and return res.send("message")
without JavaScript: route "contact"and return a redirect with a query param of "message"
Or in one route and detect xhr and render it depending on this?
Or is there a better way of dealing with the problem of taking the user to the res.send("") when the JavaScript isn't enabled to give the user feedback on the submit?
To clarify:
I have a site which is working with AJAX requests for its forms to avoid full page loads. It lacks the fallback when JavaScript is not enabled and thus when a user clicks submit on a form, he receives the data from the post back with res.send and it replaces the whole page, instead of the desired effect which would be to just update a label with the "success/fail" message. The question then remains as above which would be the neat way of dealing with this?
Probably the best thing to do would be to check the X-Requested-With header and check that it contains XMLHttpRequest (but this might get deprecated as the new fetch API will slowly come into browser.
Based on that value, you might want to return a JSON payload, or eventually trigger a server side rendering, therefore returning an HTML page ready-to-be-consumed.
As an alternative, you can return a redirect response with a particular query string value; once the page is loaded, you will check for that value (using qs for example, or deparam in jquery and manipulate the client side accordingly.
Your server routes have nothing to do with client-side javascript. You don't need javascript to receive a "res.send" message.

Caching on the Web. How are address initial visits treated in the browser?

When a visitor visits http://www.yourwebpage.com/
Is there a way to have the browser use the previously cached response? Or will it always make a request to the server?
I am guessing a request to the server will occur, but is then possible to respond with an empty string, and let the browser automatically use the cached response for index.html? Or do you always have to supply the entire answer?
The question is related to how much the initial index.html response for a JS based application should contain or if the index.html response should make a second request for html pieces and such.
// Example: Pseudo code
<html> ...
<script>
if ( !localStorage.index ) {
localStorage.index = loadFromServer( 'head.html' )
}
document.head.append(localStorage.index);
</script>
...</html>
The question boils down to, if i have ten templates.html files, which I would like to serve once, should they be included in the index.html response or should another request be made to fetch these as one bundle.
Obviously, if I make a second request, the browser will cache that response if proper headers are set, but that would cost another request, at least the first time.
If I include them in the index.html then the initial response will be bigger, but less than the two requests otherwise necessary, but how will subsequent requests to fetch the index.html be treated?
I have never visited a page who do not load something, although teoretically if the proper cached-headers from previous request has been set properly, it should be possible to treat it as an offline application, or is cache now applicable for initial requests? Only for requests made for instance by ajax or
Is the last statement true?
Basically, could you execute JavaScript by visiting a webpage using only cached data, that is without actually needing to make any request, or at least wait for an answer.
Is this possible? Perhaps storing the entire index.html in the localStorage is one way and have the index.html response the second time respond with only a script tag saying load from localStorage.
EDIT 1
I have come to understand that there is something called a Manifest for at least Firefox which can allow for the treatment as such as an application install the first time. https://developer.mozilla.org/en-US/Apps/Build/Manifest
Yes, your web server (and/or web app framework) should use cache headers to give this sort of instruction to the browser. Cache headers include etags and cache-control. A full example and explanation is here: https://www.mnot.net/cache_docs/#CACHE-CONTROL
But basically, those tell the browser when to consider the fetched content stale, when to actually make a request. Further, if the server knows the information hasn't been changed, it will respond with a HTTP 304 response, which will result in the client using the cached copy instead as well.
You really don't need to use the localstorage option unless you want your JS to definitely never ask the server for something unless it's not in localstorage. The problem with that is that you then have to manage your own cache invalidation, etc.

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.

Dynamic response with tracking pixels?

I am testing out some tracking pixel functionality in an ASP.Net 4 MVC architecture.
This article gives a nice way of setting a tracking pixel (image) that you can use to read a visitor's environment parameters and do some logging on the server side before completing the response.
What I would like to do is inject some Javascript, based on the account ID that the pixel came from. In the example above, the ID would be set by setting some query string parameters.
By the looks of that code, it can only be used to log data, as the response type is of type image.
Is it possible to accomplish this using the method shown above? If not, can I get some recommendations/sources on how to accomplish this using Javascript and tying this back into my .Net architecture where based on some logic, I can add some additional Javascript to the response?
If I have no other choice to go the JS route, I'm guessing it would be something along the lines of the Google Analytics tracking script that includes some parameters sent back through JS.
Thanks.
If the client is requesting an image and expecting an image, then that is what you need to return. Look at this type of HTML that would generate an image request:
<img src="test.jpg">
Clearing the client is expecting image bits to come back and anything besides that is going to mess up the display of that image.
If you want to put server-supplied javascript into the page, then simply have the client request some javascript like this:
<script src="test.js"></script>
Your server can then do it's logging upon that request and return whatever javascript it wants to from that request. If you want to return different javascript for every request, then you will need to defeat caching in the browser (there are a number of was to do that) so that the javascript is always requested from the server.
In general, I'm guessing that you don't need to return different javascript for every request. But rather, you can put a common block of javascript in the client page and that javascript can examine the environment and branch based upon what it finds. That's how Google Analytics works. One common piece of javascript is served to the client, that code examines the environment and then makes an ajax request with different parameters set that causes the right information to be recorded on the server.

Categories