Consuming an OData request in Sencha Touch with JSONP - jsonp

I'm working on a Sencha Touch app and I want to use OData so I have been playing around with the netflix Odata service. When I send my request with JSONP in Sencha I can see the request come back when I trace it, however my callback function is never getting called. Can anyone help? Here is my code.
var blah = function () {
Ext.util.JSONP.request({
url: 'http://odata.netflix.com/catalog/Titles()',
callbackKey: 'callback',
params: {
$format: 'json',
$top: '10',
$filter: "startswith(Name,'C')",
$select: "ShortName"
},
callback: function (result) {
alert('asdf');
var data = result;
if (data) {
alert('data');
} else {
alert('There was an error during retrieving data.');
}
}
});
}
var button = new Ext.Button({
text: 'Ajax',
listeners: {
'tap': blah
}
});
Thanks in advance

If you're getting a syntax error on the server response quotes, this is a known issue described here for which there is an available update.

The server is returning XML, not JSON data.

Related

Google OAuth2 redirect_uri_mismatch still occurring despite trying several solutions

I am currently trying to connect to Google OAuth with JS on server-side and am getting this error despite trying everything I could find on the web.
$('#sign-in-button').click(function () {
auth2.grantOfflineAccess().then(signInCallback);
});
function signInCallback(result) {
console.log(result)
console.log(typeof result)
if (result['code']) {
$('#sign-in-button').prop('disabled', true);
$.ajax({
type: 'POST',
url: 'http://localhost:8080/auth',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/json; charset=utf-8',
success: function (successResult) {
//todo next flow stage
console.log('Ready to proceed to next stage!')
},
processData: false,
data: JSON.stringify(result)
})
} else {
// todo handle error
console.log('An error occurred within the OAuth stage.')
}
}
The code above is what I am using on the client. The below code is the Express route for /auth.
app.post('/auth', function (req, res) {
if (req.header('X-Requested-With')) {
let oAuth2Client = getOAuthClient(); // this method uses return new OAuth2(clientId, clientSecret, redirectUrl) where redirect url = 'http://localhost:8080/link'.
let code = req.body['code'];
if (code) {
oAuth2Client.getToken(code, function (error, tokens) {
if (error) {
console.log(error.stack);
console.log('Whoops, an error occurred!')
res.send('An error occurred during the OAuth backend stage.')
} else {
console.log('No error.')
console.log(tokens)
google.options({auth: oAuth2Client})
}
})
} else {
//todo fail no code
console.log('Code failure.')
}
} else {
//todo return fail CSRF
console.log('CSRF failure.')
}
})
On cloud console, you can see my efforts of trying every possible URI under the sun!
Most strangely, in the Gaxios error, the URI is correct in the request body!
But I still get redirect_uri_mismatch
What can I try to fix this other than what I have listed below?
Add all the extra URI variants to cloud console
Use oAuth2Client.getAuthUrl() instead of my client side code
Different redirect URI (with & without slash etc.)

Calling POST as URL ASP.NET web api

I want to know how to test POST by typing in the url.
Here's my route Config
config.Routes.MapHttpRoute(
name: "myWebApi",
routeTemplate: "api/mywebapi/{action}/{ID}/{DeptID}",
defaults: new { Controller = "mywebapi", ID = #"\d+", DeptID = #"\d+" }
);
programmatically this is how I call POST
I have 3 text boxes and a button. When user clicks on the button the below program gets called
function parseform(button) {
var id = $("#ID").val();
var deptid = $("#DeptID").val();
var name = $("#Name").val();
var inputdata = {
id: id,
deptid: deptid,
name: name
}
if (button.attr('value') === "POST") {
postdata(inputdata);
} else {
console.log("ERROR");
}
}
function postdata(inputdata) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/mywebapi/Post/",
contentType: "application/json",
data: JSON.stringify(inputdata),
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
$("#response").text(status+" - "+data)
},
error: function (xhr, status, error) {
var json = jQuery.parseJSON(xhr.responseText);
$("#response").text(status)
}
});
}
In the controller
[System.Web.Http.AcceptVerbs("POST")]
public void Post([FromBody]mywebapi value)
{
saves to database
}
Here's what I tested
http://localhost:222/api/mywebapi/Post/new newwebapi ({"id":"1","deptid":"2","name":"testing"})
I get error. How to test this?
thanks
R
Since it's a POST request, you can't test it in your browser by typing in an address (those are GET requests, which contain no body).
To test these types of things you can use something like Postman
or Rest Console (if you're using chrome), there's tons of these types of things in whatever your browsers extension store is called.
Some tools you can use are something like Fiddler
this will let you see what the requests and responses look like, and you can change/modify them as well, though it's probably a bit harder to use than something like PostMan or Rest Console (also more powerful)

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).

Getting no records when making Ajax request

I am trying to make a request to a server but im getting no records. When i run the code I am getting no error messages so I assume my code is working but when the callback function is executed on store load I just get a blank message.
var proxy = Ext.data.proxy.Ajax.create({
type:'ajax',
url:loginHostUri,
method:'POST',
headers:{
'Accept':'application/x-www-form-urlencoded'
},
extraParams:{
grant_type:'password',
username:username,
password:psswd,
client_id: consumerKey,
client_secret: consumerSecret
},
reader:{
type:'json',
root:''
}
});
var store = Ext.getStore('instance');
store.setProxy(proxy);
store.load({
callback:function(records,operation,success){
Ext.Msg.alert('INFO',records,Ext.emptyFn);
},
scope:this
});
The message is just blank but I know the Json response looks like this:
{
"":{
"id":"2332123",
"issued_at":"090342",
" instance_url":"instance",
"signature":"sig",
"access_token":"access"
}
}
define a fields or a model for the store
store.setFields({name: 'id', name: 'issued_id' ...});(put this before store.load())
Try that and console.log(records) under callback and reply back what you get...

passing parameters to RIA service from extjs with json end point

I am trying to communicate with RIA service from extjs using POST for getting response with following code.
var store = Ext.create('Ext.data.Store', {
model: 'RootResults',
proxy: {
type: 'ajax',
actionMethods: 'POST',
url: 'MyService.svc/JSON/GetRes',
headers: {
'Content-type': 'application/json'
},
reader: {
type: 'json',
root: 'GetResResult.RootResults',
totalProperty: 'GetResResult.TotalCount'
}
, pageParam: undefined,
startParam: undefined,
limitParam: undefined
, success: function (response) {
alert(response);
}
}
});
var operation = new Ext.data.Operation({
FId: 1,
SId: 0
});
store.load({ params: Ext.encode(operation) });
i can access it with get.
when i am trying with POST, it returning error - "405 Method Not Allowed".
what to do to make it POST enabled?
When i asked this question, i am bit confused with POST communication between extjs and RIA services.
I solved this with the help of following article
http://www.joseph-connolly.com/blog/post/WCF-RIA-Services-jQuery-and-JSON-endpoint-Part-2.aspx
For accessing WCF RIA Services from jquery or extjs, actually we need to create changeset for CUD(Create-Update-Delete) operations and All of the operations use JSON/SubmitChanges.
I believe that on the server end you need to add HasSideEffects to your method declaration ():
[Invoke(HasSideEffects = true)]
public GetPages(...)
{
}