How To Make an Ajax Request inside a Azure Mobile Services api - azure

I want to make a jquery ajax post inside my azure mobile services api get method. that is, something like I have below. That is, I want the GET method to return data that returns something from ithe result of my ajax POST.
It's not obvious how I would do that.
exports.get = function(request, response) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function(x) { return MYLIST },
dataType: dataType
});
response.send(statusCodes.OK, { message : 'Hello World!' });
};
UPDATE:
Per Carlos Post : http://blogs.msdn.com/b/carlosfigueira/archive/2013/12/12/expanded-login-scopes-in-azure-mobile-services.aspx I now understand that the exports.get code should be in the API section of the azure mobile service. When I put that code into that section I get an Internal Error, 500 in my failure event of the jquery call. my alert does show I successfully logged into google.
var client = new WindowsAzure.MobileServiceClient('https://svcc.azure-mobile.net/', val);
$(document).ready(function () {
$("#submit1").click(function () {
client.login("google").done(function (results) {
alert("You are now logged in as google: " + results.userId);
$.ajax({
url: "http://xxxxx.azure-mobile.net/api/test1",
success: function (data, textStatus) {
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}, function (err) {
alert("Error: " + err);
});
});

You should use some node.js module which allows you to make HTTP requests. The simplest one is the 'request' module, which you can require on a server script and use it to make requests. For example, this code should do what you want:
exports.get = function(request, response) {
var req = require('request');
req({
url: url,
method: 'POST',
body: JSON.stringify({ theBody: [ 'hello', 'world' ]}),
headers: { "Content-Type": "application/json" }
}, function(err, result) {
response.send(statusCodes.OK, result);
}
}

Related

ReferenceError: res is not defined in NodeJS

My NodeJS Code. I am getting correct result in console but page is not redirected to listings page
function displayCities(cname) {
var pageData = {
title: "Listings",
cities: null
};
axios(
//the request
{
url: "https://sandbox.repliers.io/listings?city=" + cname,
method: "GET",
headers: {
'Content-Type': 'application/json',
'REPLIERS-API-KEY': 'SKoKOGhEO42QzdkZ1cowKgLGm2mwm4'
}
}
).then(function (response){
//on success do stuff
console.log(response.data);
pageData.cities = response.data; //store JSON results in pageData.cities (previously null)
res.render("listings", pageData);
}).catch(function (error){
console.log(error);
});
}
You have not passed the res object to the function.
To be able to access methods of the res object, you should add it to the function signature and give it to the function where you call it.

Ajax fetching HTML not SQL results from node.js

I am trying to send my sql query results from node.js to my html. When I log it in the console it shows the correct data, but once I add it to the "res.send" in a stringified format and try to retrieve it with ajax in index.html the object I get doesn't have the data, just my entire HTML code.
I've tried changing my ajax to many different things I found online but nothing changes. I've tried changing POST to GET, changing the url (which just breaks it), only using success and not complete (which results in no object coming through).
node.js code excluding server code:
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=NAME-PC\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT * FROM Companies', (err, result) => {
console.log("Works");
if(err) { // SQL error, but connection OK.
console.log(" Error: "+ err);
JSON.stringify(err);
} else { // All good.
console.dir(result);
JSON.stringify(result);
app.get('/', function data(req, res, next) {
res.send(JSON.stringify(result))
})
};
});
});
sql.on('error', err => { // Connection bad.
console.log("Bad");
console.log(" Error: "+ err);
});
HTML Ajax code:
<script>
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: 'json',
url: '/',
contentType: "application/json; charset=utf-8",
complete: function(data) {
console.log(data);
},
success: function(data){
console.log(data);
}
});
</script>
The object I end up with has a responseText that has all of the HTML code. Any idea what I am doing wrong that the response isn't my data?

Simple Json Request never succeeds

I have a very simple Express server with a single route. I want to call this route with ajax from my html page and return json to the page.
The server side function gets called successfully but the failure method of the ajax method gets called the whole time. It never succeeds.
NodeJs
app.get('/test', function(req, res) {
console.log("TEST WAS CALLED");// This Logs to Console
res.json({ message: 'Hello World' });
});
Client Ajax
function FetchData(callbackfn) {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
async:false,
cache:false,
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
callbackfn("Error getting the data")
}
});
}
function Callback(data) {
alert(data);
}

Consolidate multiple callbacks in node.js module exports

I have a sails.js service which uses restler (rest-client) to make api calls to external apis and fetch data.
The module looks like this:
var rest = require('restler');
module.exports = {
config: {
url: sails.config.remote_api.base_url.concat('/countries'),
rejectUnauthorized: sails.config.remote_api.validateSsl,
options: { 'Content-Type': 'application/json' }
},
find: function(headers, payload, callback) {
var request = rest.get(this.config.url, this.config.options);
sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });
request.on('2XX', function(data, response) {
callback(data, response);
});
}
}
In the above code request.on('2XX',...) handles the event emitted when response code is in the 200 series.
When we add other handlers for events emitted when response code is in 300, 400, 500 series...this creates a duplication of same callback function for each of the blocks. For e.g.
var rest = require('restler');
module.exports = {
config: {
url: sails.config.remote_api.base_url.concat('/countries'),
rejectUnauthorized: sails.config.remote_api.validateSsl,
options: { 'Content-Type': 'application/json' }
},
find: function(headers, payload, callback) {
var request = rest.get(this.config.url, this.config.options);
sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });
request.on('2XX', function(data, response) {
callback(data, response);
});
request.on('3XX', function(data, response) {
callback(data, response);
});
request.on('4XX', function(data, response) {
callback(data, response);
});
request.on('5XX', function(data, response) {
data = {};
data.succeeded = false;
data.failureCode = 'SYSTEM ERROR';
data.failureReason = 'A system error has occurred. Please try again. If the problem persists contact support';
callback(data, response);
});
request.on('error', function(data, response) {
data.succeeded = false;
data.failureCode = 'SERVICE UNAVAILABLE';
data.failureReason = 'The service is temporarily unavailable. Please try again later.';
callback(data, response);
});
}
}
How do we avoid the duplication of the following lines?
function(data, response) {
callback(data, response);
}
No you really shouldn't. You have been basically handling different event like 2XX, 3XX etc. Each event is handled separately and that is a good practice. Anymore simplification could damage the neat design.
Though you can directly use callback instead of
function(data, response) {
callback(data, response);
}
like this
request.on('2XX', callback);

multiple http get request node.js

This is what my code looks like for a single http get request. What I want to do is call two more http get request and store their results so I can render appropriately. Can anyone please suggests how I can achieve it? Thanks
router.get('/get_all_posts', function(req, res){
var body ='';
var options = {
host: 'localhost',
path: '/some_endpoint',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var request = http.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function (data_chunk) {
body += data_chunk;
});
response.on('end', function () {
if(response) {
res.render("something");
}
else
{
res.render('error', {error: {status:400,stack:body}});
}
});
});
request.end();
});
You should not be making http request. Whatever code you have for /some_endpoint turn it into a function, and then call that function inside router for both /some_endpoint and /get_all_posts.
Hope it helps.
This works for me.
async.map([options1, options2, options3], reqCall, function(err, results){
if ( err){
// do something
} else {
results[0]//first call
results[1]//second call
results[2] //third call
}

Resources