Getting no records when making Ajax request - sencha-touch

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...

Related

Post request with useAxios

I am trying to use the composition api on my Vue app, and I need to do a post request to my backend api. I am trying to make use of the "useAxios" utility from vueuse, but I can't figure out how to pass data into a post request. It isn't shown properly in the docs...
I want to convert the following axios request into one that uses "useAxios".
await axios.put(`/blog/posts/${route.params.postID}/`, post.value)
.then(() => notification = "Post Created!")
.catch(() => {
error = "Failed to create post"
});
I tried setting the value of the data field, but that didn't work...
const {data, execute, isFinished} = useAxios(axios)
data.value = post
await execute(`/admin/blog/posts/${route.params.postID}/`, {method: "PUT"})
I also tried passing the post object into the execute method as a parameter, but my ide complained.
Thanks in advance!
Set up your pending request ahead of time:
const { data, execute, isFinished } =
useAxios(`/admin/blog/posts/${route.params.postID}/`,
{ method: "PUT" },
{ immediate:false });
Then in the future you can call it by passing the data as follows:
const requestBody = { /* your data */ };
await execute({ data: requestBody });

Authorize to a 3rd party service within Postman request

Want to create request in Postman to cover authorization to a 3rd party within request. In application it works this way:
Client clicks the button
Application checks whether there is a token, if not it returns link to the 3rd party service to authorize there
Client follows the link, inputs credentials, submits form
Service redirects client back to the application with authorization code as a query parameter.
Client pushes another button to receive token by the authorization code.
So, is there a way to proceed this scenario within the Postman, not to copy link from response and pasting it to browser in order to complete authorization?
Tried to make request from Test script tab like:
var jsonData = JSON.parse(responseBody);
console.log(jsonData.data)
if (jsonData.data) {
pm.sendRequest(jsonData.data, function (err, response) {
console.log(response);
return response;
});
}
But that was not actually useful
There is a way to get token before request.
You can use Pre-request Script bookmark.
Write JS code to get token and save it to variable (collection / environment).
In specific request open Authorization bookmark and call your variable.
For Bearer:
My Pre-Request Script for example:
let collUsername = pm.variables.get("username");
let collPassword = pm.variables.get("password");
let collClient_id = pm.variables.get("client_id");
let collClient_secret = pm.variables.get("client_secret");
const postRequest = {
url: pm.variables.get("url"),
method: 'POST',
header: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded : [
{ key: 'username', value: collUsername},
{ key: 'password', value: collPassword},
{ key: 'grant_type', value: 'password'},
{ key: 'client_id', value: collClient_id},
{ key: 'client_secret', value: collClient_secret},
{ key: 'user_type', value: 'System'}
]
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
let jsonRes = response.json();
pm.collectionVariables.set("token", jsonRes.access_token);
});
I don't know your authentication method so your script can be different.
If you want to refresh only expired token you can add variable with date and check if appropriate time has passed to get new token.
Edit: Scripts written in Tests are executed after getting response so not proper place for your case.

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).

Consuming an OData request in Sencha Touch with 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.