Does anyone have an example of an API response being passed back from a http.request() made to a 3rd party back to my clientSever and written out to a clients browser?
I keep getting stuck in what I'm sure is simple logic. I'm using express from reading the docs it doesn't seem to supply an abstraction for this.
Thanks
Note that the answer here is a little out of date-- You'll get a deprecated warning. The 2013 equivalent might be:
app.get('/log/goal', function(req, res){
var options = {
host : 'www.example.com',
path : '/api/action/param1/value1/param2/value2',
port : 80,
method : 'GET'
}
var request = http.request(options, function(response){
var body = ""
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
res.send(JSON.parse(body));
});
});
request.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
request.end();
});
I would also recommend the request module if you're going to be writing a lot of these. It'll save you a lot of keystrokes in the long run!
Here is a quick example of accessing an external API in an express get function:
app.get('/log/goal', function(req, res){
//Setup your client
var client = http.createClient(80, 'http://[put the base url to the api here]');
//Setup the request by passing the parameters in the URL (REST API)
var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});
request.addListener("response", function(response) { //Add listener to watch for the response
var body = "";
response.addListener("data", function(data) { //Add listener for the actual data
body += data; //Append all data coming from api to the body variable
});
response.addListener("end", function() { //When the response ends, do what you will with the data
var response = JSON.parse(body); //In this example, I am parsing a JSON response
});
});
request.end();
res.send(response); //Print the response to the screen
});
Hope that helps!
This example looks pretty similar to what you are trying to achieve (pure Node.js, no express):
http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html
HTH
Related
I want to print BTC conversion to other currencies. I am using bitcoinaverage. On the browser, the URL is not working. The screen displays this "Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com". I am using Flutter. On console, it is giving a 404 error. The following is the code snippet.
const bitcoinAverageURL = 'https://apiv2.bitcoinaverage.com/indices/average/ticker';
Future getCoinData(String selectedCurrency) async {
var authKey = '$bitcoinAverageURL/BTCAUD';
http.Response response = await http.get(Uri.parse(authKey));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
double current = decodedData['last'];
return current.toStringAsFixed(0);
} else {
print(response.statusCode);
throw 'Problem with get request';
}
From documentation:
All requests to our API must be authenticated with your public key.
You need to autrhorize on API site and get your API access token. API usage described in Official documentation.
Try to add your API key to header:
await http.get(
Uri.parse(url),
headers: {
'x-ba-key': 'your_api_key',
},
);
I'm new to node and banging my head against a wall on what should be a simple node+express+googlecal+pug issue
node/express route accepts requests and calls controller
controller ensures validation of auth and then...
executes a successful gcal function...console.log has the data i need
trying to directly (in controller function) returns "Cannot set headers after they are sent to the client"....why is a call to Gcal API forcing a response back to client?
Trying to make it more micro via individual calls to each function results in same result
What am I missing here?
getcalendars: async function(oAuth2Client, res) {
const calendar = google.calendar({ version: "v3", auth: oAuth2Client });
cal = await calendar.calendarList.list(
{},
(err, result) => {
//console.log("HEADERS SENT1?: "+res.headersSent);
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(JSON.stringify(result));
message2 = JSON.stringify(result)
res.render('schedules', {message2: message2})
return
});
},
EDIT: Calling function
router.route('/dashboard/schedules')
.get(async function(req, res) {
if (req.session.loggedin) {
//x = gcalController.getcalendars(req, res);
token = await gcalController.gettoken(req, res);
isAuth = await gcalController.calauth(token);
listcalendars = await gcalController.getcalendars(isAuth,res);
} else {
res.redirect("/?error=failedAuthentication")
//res.send('Please login to view this page!');
}
});
Can't set headers already sent happens when you're sending a response more than once. Usually you can terminate the function by returning your res.send() call.
It looks like the express middleware that created the res object is sending a response by the time your res.render() gets pulled out of the microtask queue.
Can you show the full code? It seems that this is probably originating in the scope where getcalendars is called.
I'm parsing remote data in to my app and uses it through arguments. One of the data types is a url adresse i want to open in the url. I have an idea that I have to open it with the openURL function but I can't seem to get it to work. Anyone have a working example?
You have to utilize in-built HttpClient
var url = "http://www.you_remote_url.com";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();
i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
// var url = 'http://updates.html5rocks.com';
var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
but the problem still not solved:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work?
thanks
For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.
CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.
If the owner of the content doesn't want you to use it, the browser will reject it.
Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.
I have some JSONP in my application, & I want to set timeout for them. How can I set it?
it maybe something like this, if it is possible :)
Ext.util.JSONP.request({
url: mhid.dashboard.hbf.controller+'/get_dashboard'
,method: 'POST'
,timeout : 50000 // TIMEOUT
,callbackKey: 'jsonp_callback'
,params:{
'site' : site
,'fleet' : fleet
,'sn' : sn
,'format' : 'json'
}
,callback: function(response, opts) {
var obj = response;
tpl.overwrite('content', obj);
loadMask.hide();
}
,failure: function(response, opts) {
alert('Failure');
}
});
Thanks in advance
I don't think it is possible using JSONP - you should take a look at the Ext.Ajax class. Also, POST is not possible using JSONP (refer to the Sencha forum
You will need to implement your own timeout and execute the failure callback:
var failureCallback = function() {
// MUST remove the current request,
// or it will not dispatch any subsequent new JSONP request
// unless you refresh your page
delete Ext.util.JSONP.current;
alert('Failure');
};
Ext.util.JSONP.request({..}); // as usual
var failureTimeoutId = setTimeout(function() {
failureCallback();
}, 30000);
discard the timeout if your request is success
discard current request if the request has timed out