how to add headers with rest call in sencha touch? - sencha-touch-2.1

I am new to sencha development. so I don't know how to parse rest API calls in sencha?
If any one knows please help me?
example:
HTTP Method - GET
HTTP Headers
· Accept application/xml,application/json
· Authorization
· User-Agent
I want to this header with request, how to do this in sencha? Please explain with example friends. thanks in advance.

Since REST uses ajax proxy so i believe this should work. Bind beforerequest event as soon as app is launched, such that it adds certain headers to any AJAX request
Ext.Ajax.on('beforerequest', function(conn, options, eOptions){
options.headers['Authorization'] = 'BASIC YTpi';
}, this);
If you have headers which don't change you can even do this:
Ext.Ajax._defaultHeaders = {
'Accept': 'application/xml,application/json',
'Authorization': 'Basic YTpi'
};
PS I have not used it for REST so please verify before using.

Related

ODATA javascript client libraries (what is their value over simple Fetch or AJAX)?

Currently we are using client-side javascript fetch to connect to our ODATA V4 ERP server:
const BaseURL = 'https://pwsepicorapp.com/ERP10.2/api/v1/Erp.BO.JobEntrySvc/'
const fetchJobNum = (async () => {
let url = BaseURL + 'GetNextJobNum'
const reply = await fetch(url,{
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Authorization': 'Basic xxxx',
'x-api-key' : '0HXJZgldKZjKIXNgIycD4c4DPqSrzn2UFCPHbiR1aY7IW',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({})
})
let rsp = await reply.json()
let job = rsp.parameters.opNextJobNum
return job
})
And this works fine for us. We recently started looking at javascript ODATA libraries (Apache OLINGO, O.js, JayData (or other ones suggested at: https://www.odata.org/libraries/)
But what I don't see is an objective guide for a developer understand why and what these libraries provide.
I.e. I think they read the meta-data for the particular ODATA service. Fine but what does power does that add?
Perhaps my mental block is that we are only:
searching only JSON data
Not doing any nested queries (only simple $filter, $select)
Just doing simple GET, POST, PATCH
Or perhaps these libraries were needed for functionality that was missing before ODATA V4
Can anyone give a succinct description of the features for these libraries and their UNIQUE VALUE PROPOSITIONS (to borrow a Venture Capital Term) to developers? I bet others would find this useful.
Short Answer
You are right. If all you are doing just the simple operations you don't need any of these libraries as at the end of the day they are just REST calls that follow some specific conventions(i.e. OData specification).
Long Answer
The reason we have all these client side APIs is that OData offers/defines a lot more stuff.
Lets try to go though it with an example. The example I am using is Batch Requests in OData. I simplest of the terms Olingo defines a way to club multiple HTTP requests in one. It has a well defined syntax for it. That looks something like this
POST /service/$batch HTTP/1.1
Host: host
OData-Version: 4.0
Content-Type: multipart/mixed; boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Length: ###
--batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Type: application/http
GET /service/Customers('ALFKI')
Host: host
--batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Type: application/http
GET /service/Products HTTP/1.1
Host: host
--batch_36522ad7-fc75-4b56-8c71-56071383e77b--
Now there are quite a few things here.
You have to start the batch request with batch_<Unique identifier> and separate individual HTTP requests with the batch boundary, and when you are done you end it with batch__<Unique identifier>--
You set the batch identifier in as the header and send additional headers(like content-type, content-length) properly that you can see in the .
Now coming back to your original question sure you can use a lot of string concatenation in your JavaScript code and generate the right payload and make an ajax call then parse back a similar kind of response, but as an application developer all you care about is batching your GET, POST, PUT and DELETE request and operation the operation you desire.
Now if you use a client library(the example is generic and might differ from library to library) the code should look something like
OData.request( {
requestUri: "http://ODataServer/Myservice.svc/$batch",
method: "POST",
data: { __batchRequests: [
{ requestUri: "Customers('ALFKI')", method: "GET" },
{ requestUri: "Products", method: "GET" }
]}
},
function (data, response) {
//success handler
}, undefined, OData.batchHandler);
So on a purely business proposition terms libraries like these can save you quite a few man hours based on your application size that will be consumed on generating the right payload strings or right URL string(in case of filters, navigation properties etc.) and debugging thought the code in case you missed a bracket or misspelled a header name, which can be used on building the core logic for the application/product and let the standardized, repetitive and boring(opinionated thought) work for you.

fetch() doing GET instead of POST on react-native (iOS)

I have the following code in my component:
fetch('https://domain.com/api', {
method: 'POST',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
key: 'value'
})
}).
then((response) => {
console.log('Done', response);
});
And every time the request is a GET (checked server logs). I thought it was something to do with CORS (but apparently no such thing in react-native) and ATS (but already turned off by default, plus my domain is HTTPS). I've tried from a browser and from a curl and it worked perfectly, so a priori no issue on server configuration. Any idea what's going on here?
I'm using the latest react-native version.
After further digging, it was definitely an issue with the API + fetch. I was missing a slash at the end of the URL and the API issued a 301, that fetch didn't handle correctly. So I don't know if there is something to fix in the fetch function (and underlying mechanisms) but this fixed my issue :)
When a POST is redirected (in my case from http to https) it gets transformed into a GET. (Don't know why...)

Crossdomain AJAX call to Luracast Restler API: "PUT" and "DELETE" sending "OPTIONS" - Why?

I've installed Luracast's Restler API framework and am having marvelous success with it all except when sending PUT or DELETE across domains. The below works fine when all on the same server, but when I cross domains, Firebug shows the the PUT or GET as OPTIONS, and it is not found on the server. Am baffled how to stop "OPTIONS" being sent instead of PUT or DELETE.
$.ajax({
url: url,
type: 'PUT',
data: "thename="+ $('#TheName').val(),
success: function(xhr, status) {
console.info(xhr);
},
error: function(xhr, status) {
console.info(xhr.responseText);
},
complete: function(xhr, status) {
$('#showResponse').val(xhr.responseText);
}
});
Per another thread somewhere, I've added the below to the Restler output:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
You've got the right response headers, but you have to have your server respond to an OPTIONS request with those headers, too.
This is a cross-origin request, and is subject to something called preflighting. Before making the PUT or DELETE request the browser asks the target web server if it's safe to do so from a web page at another domain. It asks that using the OPTIONS method. Unless the target server says it's okay, the web browser will never make the PUT or DELETE request. It has to preflight the request, because once it's made the PUT or DELETE, it's too late to honor the response; sensitive information may have been leaked.
GET and POST are a bit more complicated, as sometimes the browser decides they are safe without asking first, while other times the browser will also do a preflight check. It depends on whether certain headers are used in the request.
The CORS spec has the gory details. The bottom line is that the code on your web page will not be allowed to make these requests unless the target web server supports the OPTIONS method, and the response to the OPTIONS method includes the headers saying that such requests are allowed.

XMLHttpRequest Post Method - Headers are stopping function

I'm trying to send an XMLHttpRequest object to my Rails server but the headers are causing my function to stop. Here are my observations:
When I comment out the 3 lines of code that set the headers, then xhr.readyState will eventually equal 4 (alert boxes within the anonymous function fire off).
If any one of the 3 header lines are uncommented, then the xhr object never changes state (none of the alert boxes ever fire off).
function saveUserProfile(){
var user_email = $('#userEmail_box').val();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200)
{
alert("Yes: " + xhr.readyState);
}
alert("No: " + xhr.readyState);
}
var method = 'POST';
var params = 'userEmail=user_email';
var url = 'http://localhost:3000/xhr_requests.json';
var async = true;
//Need to send proper header information with POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.open(method, url, async);
xhr.send(params);
}
My three questions are:
What do I need to change in the code above in order to send data through the POST method?
I'm under the impression that the POST method requires some headers to be sent but am not clear about which ones though "xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');" seems to be one that is often mentioned in references. Can somebody help me understand a) why headers need to be sent and b) which ones need to be sent?
I'm using a rails server and am developing locally. Ultimately, this code will be executed on the client side of a mobile device which will go to a hosted rails server for passing and receiving data. Are there limitations with using the POST method with a rails server? Keep in mind that I plan to use JSON when sending information to the client from the server.
Thanks!
UPDATE: The headers should come AFTER the opening the xhr request but BEFORE sending it:
xhr.open(method, url, async);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.send(params);
Hope this post saves somebody else 4 hours.
Does your web page with the JavaScript code also live on localhost:3000? If not, this is considered a cross-domain request, and your server will need to return special headers. So you have two options:
1) Host the web page on the same domain as the server, which will make this a same-domain request.
2) Have your server return the appropriate CORS headers. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Jquery-upload-progress cross domain issue. Suspected GET request problem

I am doing a site which submits a form to a different server. For upload progress tracking I use: for server side the NginxHttpUploadProgressModule und for client side - jquery-upload-progress. I have tested the setup by submitting the form to the same server and everything worked fine. Submitting to another server doesn't show the progress tracking(cross domain scripting). After hours of investigating this matter I came to the conclusion that the GET request generated by JQuery is at fault.
The query looks like this:
http://domain.com/upload/progress/?X-Progress-ID=39b2825934dbb2f33fe936df734ff840&callback=jsonp1249230337707&_=1249230345572
From the NginxHttpUploadProgressModule site:
The HTTP request to this location must have either an X-Progress-ID parameter or X-Progress-ID HTTP header containing the unique identifier as specified in your upload/POST request to the relevant tracked zone. If you are using the X-Progress-ID as a query-string parameter, ensure it is the LAST argument in the URL.
So, my question is how do I append the X-Progress-ID parameter to the end of the jquery GET request or set the X-Progress-ID header?
This doesn't work with jsonp(code from jquery.uploadProgress.js):
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Progress-ID", options.uuid);
}
Currently the request is generated this way(code from jquery.uploadProgress.js):
jQuery.uploadProgress = function(e, options) {
jQuery.ajax({
type: "GET",
url: options.progressUrl + "?X-Progress-ID=" + options.uuid,
dataType: options.dataType,
success: function(upload) {
...
I solved the GET parameter problem(code from jquery.uploadProgress.js):
jQuery.uploadProgress = function(e, options) {
jQuery.ajax({
type: "GET",
url: options.progressUrl,
dataType: options.dataType,
data: "X-Progress-ID=" + options.uuid,
success: function(upload) {
...
Modified GET request looks like this:
http://domain.com/upload/progress/?callback=jsonp1249230337707&_=1249230345572&X-Progress-ID=39b2825934dbb2f33fe936df734ff840
The nginx webserver is now correctly responding.
However as Ron Evans pointed out the client side progress tracking part won't work unless NginxHttpUploadProgressModule is modified.
You simply cannot fire an XmlHttpRequest from a webpage, to a domain different from the page's domain. It violates security definitions that are default on all browsers.
the only thing that I can think of that you can do is to use Flash or Silverlight to initiate the progress calls (Flash and Silverlight can, given the correct crossdomain.xml setup, send async requests from the browser to preset list of domains)
or, setup a browser addin (say Firefox plugin, or IE ActiveX, or Embedded WinForm control) that can initiate calls without the same-domain restriction (as the request will not originate from the webpage, but from the browser itself)
You need to install the Apache module for upload status as well, just using the jQuery plugin will not work.
To respond to Ken, I suggest you familiarize yourself with JSONP spec, since JSONP was created specifically to handle cross-domain Javascript calls.
Anyhow, this code works great in Passenger/Apache WITH my modified Apache module. Without modifying the extension for Nginx it will not work with a JSONP call.
I made a minor modification that solved the problem for me, you can check it out here:
http://github.com/tizoc/nginx-upload-progress-module/commit/a40b89f63b5a767faec3c78d826443a94dc5b126

Resources