How to call a server-side NodeJS function using client-side JavaScript - javascript

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

Related

Call WCF rest service with Javascript (JQuery) do not receive any response

The WCF service gets called for sure (the debug kicks in).
No response back to javasript callbacks.
If i configure the call with dataType:JSON the error callback is called.
If i configure dataType:JSONP no error occurs and no response is received (no callback happens neither error or sucess or done).
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json;charset-uf8",
crossDomain: false,
async: true,
url: "http://myurl",
done: function (results) {
// Uhm, maybe I don't even need this?
var parsed = JSON.parse(results);
alert(parsed);
return results;
},
success: function (data, text) {
alert(text);
alert(data);
},
error: function (request, status, error) {
alert(request);
alert(status);
alert(error);
}
});
I'm running this on localhost.
I have no clue at all, i don't even know how to get more in depth error details.
Any help appreciated.
Directly sending an HTTP request to call the WCF service applies the Restful style service. Thereby we should ensure that WCF service is restful style whereas mostly WCF service based on the SOAP web service, and the invocation is completed by using client proxy class.
From the description, I suggest you add a breakpoint on the JS statement then debug it in the browser. Besides, Success event is deprecated in Jquery, I suggest you use the Done event callback after the AJAX method.
$.ajax({
method:"Get",
url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",
contentType:"application/json"
}).done(function(data){
console.log(data);
})
I would like that you could post the code details on the server-side so that I try to make an example as much as possible.
At last, please refer to my previous demo on this topic, wish it is useful to you.
How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?
Feel free to let me know if there is anything I can help with.

Data is not ready when retrieving session parameter from the server using AJAX

I'm building an application using laravel. I have a controller which returns a session parameter from the server.
I'm retrieving this parameter using an ajax request from a view blade as follow:
var url = CMS_URL + 'GetSystemMode/';
$.ajax({
url: url,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
console.log("data: " + data);
}
});
The code running on the server side is:
Route::get('/GetSystemMode', function () {
return Session::get('systemMode');
});
In localhost, I'm getting the right "data" and the code works as a charm, but in production, "data" is always empty.
It's like the success method is executed before the data is yet retrieved from the server side.
This issue took to much time from me, and I don't have any idea how to fix it.
Thanks.
Our production environment was at the appEngine, so due to the server restirctions, it wasn't allowed to save the sessions on files as was done on localhost. So the problem was actually that the server is not saving the sessions at all and therefor I'm getting empty data.
I solved it by installing redis and saving the sessions over it.

Nodejs Facade pattern for interact with different API web services

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
});
});

Jquery Ajax Call to WEB API

I'm trying to make a simple jquery ajax call to a WEB API method.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API action:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
ajax call does not hitting the WEB API. I get the below error in browser console.
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)
Unless you are doing a cross domain call, there is no need to use jsonp (jsonp also requires a custom formatter in Web API).
$.getJSON('http://redrock.com:6606/api/values', function(data){
console.log(data);
});
EDIT:
To install a jsonp media type formatter, have a look at this project: https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Download the formatter using nuget
Register the formatter
Update your routeconfig
You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
I would suggest either renaming the action or adding the [HttpPost] attribute to your action method. You may also try the WebApiRouteDebugger package.

python code from javascript using ajax

I have seen this topic: ajax request to python script where they were trying to do exactly what I need but there is one information missing.
$.post('myPythonFile.py',{data},
function(result){
//TODO
}
);
Now my problem is: how do I call a certain function which is inside myPythonFile.py? Is there a way to specify the name of the function and to give it my input data?
Thank you very much for your time.
Ajax calls making HTTP requests,so you need to have a HTTP server which handles your requests as it is seen in the other question. (There is CGI which provide HTTP request handling). In Python you can use DJango, Bottle, CGI etc to have HTTP request handling. to call python function from javascript.
Edited :
in your url.py you should define your api url;
(r'^myAPI', 'myAPI'),
and on this url you should have a web API in views.py. It can be like ;
def myAPI(request):
callYourFunction();
and you can call it from Javascript now. You can use JQuery for AJAX request;
$.ajax({
type:"GET",
url:"/myAPI",
contentType:"application/json; charset=utf-8",
success:function (data) {
},
failure:function (errMsg) {
}
});
The HTTP method type does not matter, if you only wanna run a Python script. If you wanna send data from javascript to Python you can send the data as JSON to Python as POST method.

Categories