Error: Your session expired due to inactivity. ATG REST API session confirmation Number Missmatch - angular-http

I am working on ATG portal using REST API, all ATG API's are tested using PostMan.
It is giving an error when I started working in JS. below is the Test Code:
http({
method : "GET",
url : "http://IP:PORT/rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber"
}).then(function mySucces(response){
// localStorage.setItem("getSessionConfirmationNumer", response.data.sessionConfirmationNumber);
// localStorage.getItem("getSessionConfirmationNumer");
http({
method : "GET",
url : "http://IP:PORT/rest/model/atg/userprofiling/ProfileActor/login?_dynSessConf="+response.data.sessionConfirmationNumber+"&login=atgcust1&password=atgcust1",
// url : "http://IP:PORT/rest/model/atg/userprofiling/ProfileActor/login",
// data:formData
}).then(function mySucces(response){
console.log("done");
},function errorCallback(response) {
console.log(response);
});
});
OutPut from Console:
angular.js:10722 GET http://IP:PORT/rest/model/atg/userprofiling/ProfileActor/login?_dynSessConf=9030570900570011195&login=atgcust1&password=atgcust1 409 (Conflict)(anonymous function) # angular.js:10722p # angular.js:10515g # angular.js:10222(anonymous function) # angular.js:14745n.$eval # angular.js:15989n.$digest # angular.js:15800n.$apply # angular.js:16097(anonymous function) # angular.js:23554n.event.dispatch # jQuery-2.1.4.min.js:3r.handle # jQuery-2.1.4.min.js:3
functions.js:75
Object {data: "Your session expired due to inactivity.", status: 409, config: Object, statusText: "Conflict"}
Session Confirmation Number Can be Accessible only once after that it will give 500 internal server error (This Logic I have written not included here),
Login is working when I get session confirmation Number manually from browser and giving that as _dynSessConf value manually in the code
Please help.

Some JSON libraries like org.json have a problem parsing large longs.
They yield a slightly different value for large longs which is exactly happend to my code,
SessionConfirmationNumber Returning Via JSON as Data type of Long and I was getting rounded value as the SessionConfirmationNumber was large.
I have used xmlHttp request for solving this issue.
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://IP:PORT/rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber", false );
xmlHttp.send();
console.log(xmlHttp.responseText);
Thank God :)

Related

Meteor Get request

Bear with me for any mistakes/wrong terminology since I am new to all this. I am using meteor to develop my project and i need to make a get request to an external API. (I already added meteor add http) Below is my code:
HTTP.call( 'GET', 'url', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
If i use the code inside my Client folder in Meteor I get the following error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access meteor It has something to do with CORS which I didn't understand how to implement. If I use the code above in my Server side I do get the correct response in the console but how do I use it as a var on my client javascript code?
Tou can use .call function of HTTP and pass your header in options:
HTTP.call(method, url, [options], [asyncCallback])
Arguments
method String
The HTTP method to use, such as "GET", "POST", or "HEAD".
url String
The URL to retrieve.
asyncCallback Function
Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.
Options
content String
String to use as the HTTP request body.
data Object
JSON-able object to stringify and use as the HTTP request body. Overwrites content.
query String
Query string to go in the URL. Overwrites any query string in url.
params Object
Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL.
auth String
HTTP basic authentication string of the form "username:password"
headers Object
Dictionary of strings, headers to add to the HTTP request.
timeout Number
Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.
followRedirects Boolean
If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true.
npmRequestOptions Object
On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation.
beforeSend Function
On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send.
Souce: Here
Fixed it. On client side
Meteor.call("getURL",'url',{},function(err,res){
if(err){
console.log('Error: '+err);
}
if(!err){
console.log('Response: '+res);
}
and on server
Meteor.methods({
'getURL': function(url_l){
console.log("Request: "+url_l)
return HTTP.get(url_l)
}
});

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

Writing an async test with Intern

I am trying to write an Integration test which calls my real service (that returns JSON) and makes sure the format of the JSON is OK.
I get an error
Error: Unable to load http://localhost:7200/users/signoff status: 0
ErrorCtor#http://localhost:9000/resources/www/tests/lib/dojo/errors/create.js:29
onError#http://localhost:9000/resources/www/tests/lib/dojo/request/xhr.js:133
I've got a service that has the actual functions to interact with the server and it returns promises from every function. My test looks like this.
define([
'intern!bdd',
'intern/chai!expect',
'app/services/myService'
], function (bdd, expect, MyService) {
with (bdd) {
describe('Service Tests', function () {
var service;
before(function () {
service = MyService.getInstance();
});
it('should sign user off', function(){
var dfd = this.async(2000);
service.signUserOff().then(dfd.callback(function (data) {
expect(data).to.exist;
expect(data.status).to.exist;
}), dfd.reject.bind(dfd));
});
});
}
});
service.signOff() makes a call to the real service and then returns a promise. I have tried this with Firefox and PhantomJS both and I keep getting this error. The weird thing is, the URL in the error works fine if loaded manually in the browser.
I wonder if this is something to do with Intern not being able to load the request/xhr.js and therefore throwing this error?
The request that you are making is considered a cross-site request, so you need to either make sure your server correctly responds with the appropriate CORS headers for such a request, or you need to set up a reverse proxy that ensures that the XHR requests are occurring through the same origin.

Cross Domain AJAX Post using easyXdm

I am trying to get a cross domain AJAX post to work using the easyXdm library.
In my local development environment I have two sites:
1. http://localhost/MySite/ws/easyXDM/cors/index.html (EasyXdm file)
2. http://localhost/MyClientSite/TestPage.html (AJAX post from here)
TestPage.html (AJAX Post)
var rpc = new easyXDM.Rpc({
remote: "http://localhost/MySite/ws/easyXDM/cors/index.html"
},
{
remote: {
request: {}
}
});
rpc.request({
url: "http://localhost/MySite/ws/MyService.asmx/DoSomething",
method: "POST",
data: jsonData
}, function(response) {
console.log(JSON.parse(response.data));
$('#thanksDiv').fadeIn(2000, function () {
$('#thanksDiv').fadeOut(4000);
});
});
When I do the AJAX post I get the following in my browser's console:
easyXDM present on 'http://localhost/MySite/ws/easyXDM/cors/index.html?xdm_e=http%3A%2F%2Flocalhost%2FMyClientSite%2FTestPage.html&xdm_c=default884&xdm_p=4
native JSON found
easyXDM.Rpc: constructor
{Private}: preparing transport stack
{Private}: using parameters from query
easyXDM.stack.SameOriginTransport: constructor
easyXDM.stack.QueueBehavior: constructor
easyXDM.stack.RpcBehavior: init
{Private}: firing dom_onReady
... deferred messages ...
easyXDM.Rpc: constructor
{Private}: preparing transport stack
{Private}: using parameters from query
easyXDM.stack.SameOriginTransport: constructor
easyXDM.stack.QueueBehavior: constructor
easyXDM.stack.RpcBehavior: init
... end of deferred messages ...
easyXDM.stack.SameOriginTransport: init
easyXDM.stack.RpcBehavior: received request to execute method request using callback id 1
easyXDM.stack.RpcBehavior: requested to execute procedure request
easyXDM.stack.QueueBehavior: removing myself from the stack
Problem: The web service never actually receives the data. This is obvious as my AJAX post success function should show a thanksDiv and also a record should be created in the *database.
Note: I am replacing my existing AJAX post code as I need to use easyXdm to overcome an issue with Internet Explorer 6 and 7 on a client's site.
Additional Information:
The file-structure where my easyXdm files are located is as follows:
/ws/easyXDM/easyXDM.debug.js
/ws/easyXDM/easyXdm.swf
/ws/easyXDM/json2.js
/ws/easyXDM/name.html
/ws/easyXDM/cors/index.html
My web service was throwing a HTTP 500 server error as jsonData was not being sent correctly via easyXdm.
The json data looks like this before it was posted:
{ "param1": "value1", "param2": "value2"...... }
However, the web service was receiving the data one character per line e.g.
{
"
p
a
r
a
m
"
....
I was not serialising the json data prior to my post. So, based on the original code I posted in the original question:
To get it working I changed the line
data: jsonData
to
data: JSON.parse(jsonData)

Looks like Meteor.http.post is not working properly

I'm trying to post on a user's facebook feed from the server side of Meteor app:
result = Meteor.http.call 'POST',
"https://graph.facebook.com/#{facebook_id}/feed?access_token=#{app_access_token}",
{ data: { message: "some message", link: "http://www.somelink.com" } }
I got the following as a result:
{"statusCode":400,"content":"{\"error\":{\"message\":\"(#100) Missing message or attachment\",\"type\":\"OAuthException\",\"code\":100}}","headers":{"access-control-allow-origin":"*","cache-control":"no-store","content-type":"text/javascript; charset=UTF-8","expires":"Sat, 01 Jan 2000 00:00:00 GMT","pragma":"no-cache","www-authenticate":"OAuth \"Facebook Platform\" \"invalid_request\" \"(#100) Missing message or attachment\"","x-fb-rev":"710505","x-fb-debug":"doa24fNWaPsogxv4HmXa1/5KA30BBct86VZWVeYsins=","date":"Fri, 11 Jan 2013 13:57:52 GMT","connection":"keep-alive","content-length":"95"},"data":{"error":{"message":"(#100) Missing message or attachment","type":"OAuthException","code":100}},"error":{}}
I tried to reproduce this problem in Facebook debugger - I got the same message only if I do not send any parameters in POST body. Could it be the problem of POST implementation in Meteor.http.call?
You're sending your data in the HTTP POST request content body data, you need to use params to pass the correct variables on as postdata
try
result = Meteor.http.post(
"https://graph.facebook.com/#{facebook_id}/feed?access_token=#{app_access_token}",
{ params: { message: "some message", link: "http://www.somelink.com" } } );
Also if you're diong this in a Meteor.methods stub try using this.unblock(); so that other operations can occur simultaneously
Update: The newer versions of meteor use HTTP instead of Meteor.http, the code above would go as HTTP.post as a drop in replacement.

Resources