I am working with a NodeJs App and I have to call to a online web service in the logic part.
The problem is that if that web service is taken down, the whole system stop working.
To deal with this I have though in use a Facade pattern, adding another web service with the same functionality, and one offline file with similar information (but not as good as the web service's).
The idea is call the Facade (javaScript file?) from the logic part. It has to choose first the primary web service and call it, if it is down, go for the second one, and if it is also down, call the offline data file.
Any idea about how to stucture this on NodeJS?
This is a possible solution
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl1'
}).then(function (response) {
// this callback will be called asynchronously
// when the response is available
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// In case it fails
$http({
method: 'GET',
url: '/someUrl2'
}).then(function (response) {
// this callback will be called asynchronously
// when the response is available
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// If it fails again, use JSON file here
});
});
Related
I'm working on creating a basic login system, and since the server-side uses NodeJS, but client-side doesn't. I have to make any calls that use NPM packages on the server side. The issue is I have no clue how to call a server-side NodeJS function from the Client-Side JavaScript. Basically I wan't to be able to call a function that's stored on the server from the client browser.
Make a route in your nodejs application like so:
app.get('/users', function(req, res) {
// Your function to be called goes here.
});
Now you can call this code from your client side javascript using ajax. Like this:
$.ajax({
type: 'GET'
url: 'http://localhost:8000/users',
success: function(response) {
console.log(response);
},
error: function(xhr, status, err) {
console.log(xhr.responseText);
}
});
Create a REST API and map the request parameters to the specific function calls you need to use. See this tutorial on creating REST APIs.
You do this by calling APIs on the server (a specific url that will to some specific work).In JS you need ajax. Have a look here
//url be the api like '/api/something/'
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
// your response
}});
});
in Node we have axios that will do the same
example
axios.post('api/tobackend/function',{user:'a',password:'b'})
.then((res)=>console.log('response from server'))
in backed you might need route to handle the request.
router.post('api/tobackend/function',(reqs,resp)=>{console.log('backend')})
With Socket.io
in JS
let xhr = new XMLHttpRequest(); xhr.open('GET', '/user/sessionDestroy'); xhr.send();
In Node.JS
I'm really curious if someone can better explain the internal workings of excel's addin caching of javascript functions? I'm running a flask app on my own internal website behind a SSL cert. My addin pulls in this functionfile.html, and makes an ajax call back to mysite:
<script>
// After the Office library builds, it will look for Office.initialize
// which must be passed a function. It doesnt have to do anything though.
Office.initialize = function (reason){
$(document).ready(function(){
registerBindings();
});
}
function getData(){
return Excel.run( function (context) {
// request bindings
var state_nbr = context.workbook.bindings.getItem("state_nbr").getRange().load("values");
// and the rest for the ajax call
return context.sync().then( function () {
$.ajax({
type: "GET",
url: "https://example.com/excel/function",
data: {
"state_nbr": state_nbr.values[0][0]
}
}).done( function (data){
context.workbook.bindings.getItem("test").getRange().values = [["done"]];
return context.sync();
}).fail( function (result){
context.workbook.bindings.getItem("test").getRange().values = [["fail"]];
return context.sync();
});
});
});
}
</script>
When I click my button, I can see the request with the right payload going to example.com/excel/function, which is a flask route that pumps out a bunch of CLI junk (hundreds of logging commands).
What gets weird though, is that after that first click every time I click the button I don't get any new ajax requests, I only get a request for the functionfile.html. But SheetA1 still pops up "done".
I thought this was just storing the results in cache, but even with flask running in debug mode, if I change functionfile.html, say [["done"]] to [["finished"]], no new ajax call is detected in my logs. BUT THE SHEET UPDATES?!
I want to make a HTML using javascript to do the following task:
loading a HTML such as here
put the stock price value in a variable
display using that variable for calculation
You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you to do that. Your only option should be making a server-side call then do whatever you want
Contact that provider and request/buy access to their information. They might provide you with an endpoint of a Web API (or other service). You can then access it through (for instance) AngularJS:
// Simple GET request example:
$http({
method: 'GET',
url: 'http://somehosturl/api/stockprices/' // or whatever
}).then(function successCallback(response) {
$scope.stockPrices = response;
}, function errorCallback(response) {
HandleError(response);
});
(based on their general usage sample)
I'm trying to send Ajax request using jquery and HTML5.
I have several pages in my application.
Is it possible to make Ajax request on a page(e.g sync.html) and receive response on a different page(e.g home.html).
I know there are other approaches to this like web-sockets and long pooling but if it's possible to achieve this using Ajax then that will make my work easier preventing me from changing any server configurations.
I'm using ASP.NET,C# on the server side.
The reason why I'm doing this is to prevent users from waiting for the response before they resume doing any other activity because this might take long depending on the size of data sent to server and the internet speed.
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: server_url,
data: {
number_chunksdone : num_chunksdone,
sync_data: round_1_sync_data,
organisation_id: organisation_id,
sync_id: sync_id,
instrument_id: instrument_id,
user_id: user_id,
sync_data_2: round_2_sync_data
},
success: function (j) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Any idea?
You can try writing Location.replace() or Location.assign() method inside success function. For e.g., document.location.replace('home.html');
The Location.replace() method replaces the current resource with the one at the given URL.
EXT JS - I would like to know how to check the json response for a session time out like if a user is idle for say 20 minutes or so if his session is expired or not
There is no standard way of handling session timeouts in ExtJS. ExtJS is a client-side library, used to create the user interface/front-end layer of an application, while session management takes place on the server side.
ExtJS Ajax requests implement a callback mechanism. It means that a certain Javascript function is assigned as the callback function, which is called when the Ajax request has finished (either successfully or unsuccessfully). Here's an example taken from ExtJS API Documentation - see parameters success and failure that define the callback functions:
// Basic request
Ext.Ajax.request({
url: 'foo.php',
success: someFn,
failure: otherFn,
headers: {
'my-header': 'foo'
},
params: { foo: 'bar' }
});
So, in the case of session timeout, you could (for example) construct a JSON response, which would contain some error code (defined by you), and an error message to be shown to the user. The callback function should then check if this error is returned from the server, and take necessary actions (show error message, redirect to login page, etc.) when that happens.
Note that in the above case, from ExtJS viewpoint, the Ajax request would actually be successful. When the HTTP request fails altogether (HTTP errors like 403 and such), the Ajax request is considered unsuccessful. This is important because it is usually possible to define different callback functions for successful and unsuccessful requests (as in the above sample code).
You can mock the timeout session...
var keepaliveHandler = new Ext.util.DelayedTask(function(){
Ext.Ajax.request({
url : '/keepalive',
method : 'GET',
success: function(response, options){
//dummy server call each 60 seconds
keepaliveHandler.delay(60000);
}
});
});
var timeoutHandler = new Ext.util.DelayedTask(function(){
//invalidate session
Ext.Ajax.request({
url : '/logout',
method : 'GET',
success: function(response, options){
Ext.MessageBox.show({
title: MessagesMap.getMessage('session.closed'),
msg: MessagesMap.getMessage('session.closed.message'),
buttons: Ext.MessageBox.OK,
fn: function() {
window.location.pathname = '/';
},
icon: Ext.MessageBox.WARNING
});
}
});
});
if(Ext.ux.SystemProperties.isLogged) {
keepaliveHandler.delay(60000);
timeoutHandler.delay(Ext.ux.SystemProperties.timeout);
//check for mouse movements
document.body.onmousemove = function(e) {
timeoutHandler.delay(Ext.ux.SystemProperties.timeout);
};
}