Titanium post httpclient fail second time - titanium

Stuck with this for several days already. I already google but there is no advice on this. So any help is appreciated a lot. I recently work with posting JSON data to web service Titanium. For example: I made a service to register and unregister a module. First, when I register with this module:
var xhr = Ti.Network.createHTTPClient({
enableKeepAlive: false
});
xhr.timeout=2000;
xhr.onerror=function(){};
xhr.onload = function(e){
//Ti.API.info(this.responseText);
var response= JSON.parse(this.responseText);
//Ti.API.info(response.err+' '+response.msg);
if (response.err==0){
alert(response.msg);
win.close();
};
var link='https://dttc.haui.edu.vn/RegisterSubject';
xhr.open('POST',link);
var params=({
s:Ti.App.Properties.getString('Student_ID',''),
t:win.trainingid
});
xhr.send(params);
It works perfectly. Then I unregister with the same code but in different window with different link, it freeze my app even it does the unregister:
var xhr = Ti.Network.createHTTPClient({
enableKeepAlive: false
});
xhr.timeout=2000;
xhr.onerror=function(){};
xhr.onload = function(e){
//Ti.API.info(this.responseText);
var response= JSON.parse(this.responseText);
//Ti.API.info(response.err+' '+response.msg);
if (response.err==0){
alert(response.msg);
win.close();
};
var link='https://dttc.haui.edu.vn/UnRegisterSubject';
xhr.open('POST',link);
var params=({
s:Ti.App.Properties.getString('Student_ID',''),
t:win.trainingid
});
xhr.send(params);
Please leave any comments if u have any suggestion?

Related

Can fetch() do responseType=document?

XHR's responseType='document' is awesome because it hands you back a DOM document that you can use querySelector, etc on:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
var document = e.target.response;
var h2headings = document.querySelectorAll('h2');
// ...
};
Is this possible with the fetch method?
It's not natively supported in fetch as the API is a purely network-layer API with no dependencies on being in a web browser (see discussion), but it's not too hard to pull off:
fetch('/').then(res => res.text())
.then(text => new DOMParser().parseFromString(text, 'text/html'))
.then(document => {
const h2headings = document.querySelectorAll('h2');
// ...
});

Pexels API HTTP Authorization Header

I just started learning about APIs and I am trying to use the pexels API found here: https://www.pexels.com/api/
I have gotten the API Key, however I am not sure where to put my API key at.
I want the result to display JSON.
When I run this code on bash it works, however, I am not sure how to do it inside javascript.
curl -H "Authorization: YOUR_API_KEY" "http://api.pexels.com/v1/search?query=people"
I am running express and request.
This is my code.
var express = require("express");
var app = express();
var request = require("request");
app.set("view engine","ejs");
var url = "http://api.pexels.com/v1/search?query=example+query&per_page=15&page=1";
request(url, function(error,response, body){
if(!error && response.statusCode == 200){
console.log(body);
}
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("server is running!");
});
Any help is greatly appreciated as I am new to this and tried to Google for an answer but couldn't. Thank you!
You need to add header to make api calls,
The code goes this way,
var express = require("express");
var app = express();
var request = require("request");
app.set("view engine","ejs");
var data = {
url : "http://api.pexels.com/v1/search?query=example+query&per_page=15&page=1",
headers: {
'Authorization': 'Your-Api-Key'
}
}
request(data, function(error,response, body){
if(!error && response.statusCode == 200){
console.log(body);
}
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("server is running!");
});

Slice ArrayBuffer with Safari and play it

I need to load a mp3, slice and play it using web audio , on firefox a slice mp3 any where and decode work fine, but on safari an error with null value occurs. Exist a trick or a way do slice the ArrayBuffer on Safari?
player.loadMp3 = function(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var mp3slice = request.response.slice(1000,100000);
player.context.decodeAudioData(mp3slice); // context is webkitAudioContext on safari
callback();
};
request.send();
};
I need to create a mp3 player with some especial features:
Time shift the music (like http://codepen.io/eranshapira/pen/mnuoB)
Remove gap between musics ( I got this slicing ArrayBuffers and join then with a Blob but only in safary/IPAD don't work).
Cross platform (IPAD and android. I'm using apache cordova for that).
Solution
player.loadMp3 = function(url, callback) {
console.log("loading " + url);
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
console.log("loaded");
console.log("decoding...");
player.context.decodeAudioData(request.response, function(buffer) {
console.log("decoded");
player.buffer = player.joinAudioBuffers(player.buffer,buffer,2000000);
player.duration += player.buffer.duration;
player.time = minsSecs(player.buffer.duration);
console.log("concatenated");
callback();
});
}, function() {
alert("decode failure");
};
request.send();
};
The code you've shown shouldn't work on any browser. For one thing you need to provide a callback function to decodeAudioData. You also need to slice the decoded data after decoding it, not the raw mp3-encoded data before decoding it. Some browsers might be able to decode a slice of the mp3 file, but it's not expected. Something like this:
player.loadMp3 = function(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var mp3slice = request.response.slice(1000,100000);
player.context.decodeAudioData(mp3slice, function(decoded) {
var pcmSlice = decoded.slice(1000, 100000);
callback(pcmSlice);
});
};
request.send();
};
I haven't tested this code.

cant sent data from opera browser using HttpRequest

I can sent data to server using HttpRequest from all browser apart from opera browser. I tired opera 11.61 too. But still i cant sent data to server from opera browser.My code is
xmlHttp=new XMLHttpRequest();
var url="http://localhost";
xmlHttp.open("POST",url,true);
var params = "lorem=ipsum&name=binny";
function timerMethod()
{
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);
}
Please help me in this issue
With Regards,
Muthu.S
This should work provided you call timerMethod() from elsewhere in the code as hallvors alluded to. For example:
xmlHttp=new XMLHttpRequest();
var url="http://localhost/stackoverflow/response.php";
xmlHttp.open("POST",url,true);
var params = "lorem=ipsum&name=binny";
function timerMethod()
{
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);
xmlHttp.onload = function(){
console.log( this.responseText );
}
}
timerMethod();

How do I write a Node.js request to 3rd party API?

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