How to write curl -XGET command in ajax - ajax

I am running this command (this works):
$ curl -XGET http://localhost:15439/logstash/thresholds
And I want to write it in AJAX.
$.ajax({
url: "http://localhost:15439/logstash/thresholds",
method: "GET",
dataType: "json",
success: function(data) {
var json_response = data;
console.log("success");
console.log(data);
},
error: function(error) {
console.error(error);
}
});
But it refuses for:
"OPTIONS http://localhost:15439/logstash/thresholds
net::ERR_CONNECTION_REFUSED"
Any idea why?
When I run curl -XGET -v http://localhost:15439/logstash/thresholds I get:
* About to connect() to localhost port 15439 (#0)
* Trying ::1...
* Connected to localhost (::1) port 15439 (#0)
> GET /logstash/thresholds HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:15439 > Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Content-Length: 2510
< ETag: W/"H7IFEeDwS43oKpCDN92CPQ=="
< Date: Wed, 21 Jun 2017 07:32:57 GMT
< Connection: keep-alive

Related

How do I GET an Amazon S3 presigned url's object from jQuery Ajax

I can find nothing on Google.
I am properly creating presigned urls because they do work if I use a browser to load the request.
However, when using the identical url from a jQuery ajax call it is failing and telling me the request signature is wrong.
PS: Here are the headers. First section is from successful browser call and second section my ajax failure.
HTTP/1.1 200 OK
x-amz-id-2: clb7J//+XLYa+XS4HJthLdDO0KxBJU02fyBt29Kr8A2TXRJXM189tGgy7bWgmoYkDzXWUhg3R5g=
x-amz-request-id: F3A8C4ED98E5443E
Date: Mon, 04 May 2015 21:53:24 GMT
Access-Control-Allow-Origin: <any valid value>
Access-Control-Allow-Methods: GET, DELETE, HEAD
Access-Control-Allow-Headers: accept, content-type
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Content-Length: 0
Server: AmazonS3
BAD AJAX:
HTTP/1.1 403 Forbidden
Access-Control-Allow-Origin: <any valid value>
Access-Control-Allow-Methods: GET, DELETE, HEAD
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
x-amz-request-id: 05071412E03C4541
x-amz-id-2: xw5uMr2N/alPOR7MFMbX6fVkVEf1p30VhQKyP3yUqxYXxDq+vb5hzlsyShHwY4XhgAfLd3BCjG0=
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Mon, 04 May 2015 21:53:24 GMT
Server: AmazonS3
Here is my Ajax call:
$.ajax({
type: "GET",
url: presignedurl,
contentType: 'application/json; charset=utf-8',
cache: false,
async: true,
dataType: "text",
error: function (xhr, status, error) {
CentralScrutinizer("FetchDetails Exception: " + error);
},
success: function (payload) {
try {
$('#newTaskDetails').val(payload);
} catch (e) {
}
}
});
The specific error is:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>SignatureDoesNotMatch</Code><Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
Again, the closest I could find was a similar SO post for a put but they merely suggested adding the following headers:
//headers: { 'Content-Type': 'application/json; charset=utf-8' },
I tried that but it made no difference.
I also used fiddler to compare the two GETs (browser versus ajax) and the only thing different I see is the jsonp callback parameter.
That shouldn't affect the signature, should it?
Here are the headers
Browser Success:
HTTP/1.1 200 OK
x-amz-id-2: clb7J//+XLYa+XS4HJthLdDO0KxBJU02fyBt29Kr8A2TXRJXM189tGgy7bWgmoYkDzXWUhg3R5g=
x-amz-request-id: F3A8C4ED98E5443E
Date: Mon, 04 May 2015 21:53:24 GMT
Access-Control-Allow-Origin: <any valid origin>
Access-Control-Allow-Methods: GET, DELETE, HEAD
Access-Control-Allow-Headers: accept, content-type
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Content-Length: 0
Server: AmazonS3
BAD AJAX:
HTTP/1.1 403 Forbidden
Access-Control-Allow-Origin:: <any valid origin>
Access-Control-Allow-Methods: GET, DELETE, HEAD
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
x-amz-request-id: 05071412E03C4541
x-amz-id-2: xw5uMr2N/alPOR7MFMbX6fVkVEf1p30VhQKyP3yUqxYXxDq+vb5hzlsyShHwY4XhgAfLd3BCjG0=
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Mon, 04 May 2015 21:53:24 GMT
Server: AmazonS3
Thanks!
I found the answer.
I removed the following from the Ajax request:
contentType: 'application/json; charset=utf-8',
And it worked just fine.
I figured this out by comparing the response headers and subtracting what was common between the two.
Once I got the similarities out the only differences were content-length and content-type.
So as an experiment I simply commented out the contentType attribute and it worked.
That does not happen too often with s3 signatures and ajax. I feel I got lucky and hope this helps someone.

AJAX CORS webAPI request fails even after the preflight OPTIONS succeeds

I am trying to make CORS AJAX "GET" call to an web API service hosted in a test server. webAPI URL = http:xxx:xxx:xxx:xxx/api/v1/jobs
I have the following lines of code in WebAPIConfig.cs
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
AJAX request (from local)
$.ajax({
type: "GET",
datatype: "JSON",
url: http: xxx: xxx: xxx: xxx / api / v1 / jobs,
contentType: "application/json";
charset = utf - 8 ",
accept: 'application/json',
beforeSend: BH,
success: callback
}).done(function (data) {
var str = data.job_id + ': ' + data.job_name;
$('#responsevalue').text(str);
}).error(function (jqXHR, textStatus, errorThrown) {
$('#responsevalue').text(jqXHR.status + "::" + jqXHR.statusText + "::" + jqXHR.responseText );
});
In Fiddler, I can see the pre-flight request with OPTIONS being sent and the response with 200.
Fiddler Request Headers:
OPTIONS http:xxx:xxx:xxx:xxx/api/v1/jobs HTTP/1.1
Host: 50.17.211.226
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Fiddler Response Headers
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 14:21:50 GMT
Content-Length: 0
In Firebug, i can see the following details:
Firebug Request Headers:
OPTIONS http:xxx.xxx.xxx.xxx/api/v1/jobs HTTP/1.1
Host: xxx.xxx.xxx.xxx
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http:localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Firebug Response Headers:
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *, *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept, Content-Type
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 18:08:36 GMT
Content-Length: 0
I read lot of documentation here and in other places. It seems pretty simple and works for everyone (except me).
Final note: I tested the API with the html page residing in side the test server an it worked fine. Meaning the service and the web page both residing in the same domain.
Additional Info: Browser: Firefox, ASP.NET 4.5, web API 2.2, VS2013 Express
Thanks in advance and any help will be much appreciated.
In your response, it says the allowed headers are Content-Type, Accept, Content-Type, but you are asking for requestdateutc,requestverificationtoken. Try explicitly allowing those headers.

Ajax post sometimes removes body and adds NTLM Authorization

We're experiencing some problems with some ajax calls. On the server side we're running Apache Tomcat with Servlets. On a few calls an Authorization (NTLM) is added in the request header,
and the post body is removed. We are using NTLM authentication on the site, but authentication is already done before these ajax calls are made, and this only happens on certain ajax calls.
Here the JavaScript making the Ajax call.
var postObjects = function(f, parameter, value, variables)
{
var post = {};
post['f']=f;
post['courseid']=trapi.courseID;
post['courseresourceid']=trapi.courseResourceID;
post['mode']=trapi.mode;
if(parameter!=null)
post['parameter']=parameter;
if(value!=null)
post['value']=value;
if(variables!=null)
{
for(var i=0; i<variables.length;i++)
{
post[variables[i][0]]=variables[i][1];
}
}
var returnString="";
$.ajax(
{
url : location.pathname,
data:post,
cache:false,
global:false,
dataType:'text',
contentType:'application/x-www-form-urlencoded; charset=UTF-8',
type:'POST',
async:false,
success: function(data)
{
returnString=data;
},
error: function(jqXHR, textStatus,errorThrown)
{
returnString="Error: "+textStatus;
}
});
return returnString;
}
And here is info from fiddler about a POST made by the postObjects function which adds NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
Authorization: NTLM BASE64ENCODEDSTRING
Content-Length: 0
And here is info from fiddler about a POST made by the same postObjects function not adding NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 61
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
f=getlasterror&courseid=909&courseresourceid=4079&mode=normal
Do I have to re-authenticate each time this happens?

400 bad request error using ajax

I am using ajax to call a webservice. But when i check the ouput in firebug i get 400 bad request error. Can you please tell me why do i get the error. Why do i get the error. Is anything wrong in following code.Following is the code i have written:
<script>
function HelloWorld() {
var sDate = '<cart currency="USD" total="5.38"><cart-shipment total="5.38" shipment-reference="33261668"><shipment-tax total="0.39" /><shipment-cost total="0" /><shipment-address><address>33 W 59TH STREET APT 203 </address><zip>60559</zip><city>WESTMONT</city><state>IL</state><country>US</country><phone></phone><name>John Baker</name><attention-of>KID</attention-of></shipment-address><items><item total="4.99"><item-name>Hello Kitty - cupcake</item-name><item-description>Hello Kitty - cupcake</item-description><item-price>4.99</item-price><item-quantity>1</item-quantity></item></items></cart-shipment></cart>';
var webMethod = "https://abc.com/Services/TransactionService.svc";
var sr = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:ns2="vp">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<tem:ProcessTransaction>' +
'<tem:checkOutData>' + sDate + '</tem:checkOutData>' +
'<tem:token>5OMc0y1miZN5EFqiZ8IiLn+mzdboyTuTob43Kp4+VcVtrYGQvl7QWJB5OeoPWQpBUej6LSejwE8f16tDhg1EUqDtGGAdn/MM3Gk8MOr0FvFko84ogfhIs9HCUjum2MUN1a/sALjhen+DareUP5wWbIpnu8Eaqg2Tv0RjEsq1bqYblHcXfKIq7anTDzYoHN8Y7LAXgdEhSrVcEIB3+sCCDQ==</tem:token>' +
'<tem:transactionDescription>Volusion Order Description</tem:transactionDescription>' +
'</tem:ProcessTransaction>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
$.ajax({
type: "POST",
url: webMethod,
data: sr,
contentType: "text/xml",
dataType: "xml",
cache: false,
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data);
}
function OnError(request, status, error) {
alert(error);
}
</script>
<div>
<input type="button" value="Soap" onclick="HelloWorld();" />
</div>
Following is the output that i receive in firebug:
Request Headers:
OPTIONS /Services/TransactionService.svc?wsdl HTTP/1.1
Host: development.virtualpiggy.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://test.com
User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
Access-Control-Request-Headers: origin, content-type, accept
Accept: /
Referer: http://test.com/Desktop/test_webservice.htm
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Response Header:
Access-Control-Allow-Origin:http://yann-asus:81 http://www.kkdmarketing.com
Cache-Control:private
Content-Length:0
Date:Tue, 04 Dec 2012 06:42:23 GMT
Server:Microsoft-IIS/7.0
Set-Cookie:SessionId=ovpsrxt33jyoi3pzidvxkh0o; path=/; secure; HttpOnly
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
I would try setting a utf-8 charset in the contentType
$.ajax({
type: "POST",
url: webMethod,
data: sr,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
cache: false,
success: OnSuccess,
error: OnError
});

JQuery-Ajax headers issue

I got a problem with the headers when i'm trying to do a POST Request with JSON
This is the code:
$.ajax({
type: "POST",
url: url,
data: jsonData,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
error: function(){
alert("Fail");
},
success: function(){
alert("Success");
}
});
And this are the Request Headers displayed by Firebug.
OPTIONS /path HTTP/1.1
Host: 192.168.15.109:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0 FirePHP/0.7.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
x-insight: activate
Pragma: no-cache
Cache-Control: no-cache
And the Response Headers:
HTTP/1.1 204 No Content
Date: Thu, 24 May 2012 19:17:01 GMT
Allow: OPTIONS,POST
As you can see, the headers doesnt match with the ones im specifying, but when i use CURL the Headers are this ones instead:
POST /path HTTP/1.1
User-Agent: curl/7.25.0 (i386-pc-win32) libcurl/7.25.0 OpenSSL/0.9.8u zlib/1.2
Host: localhost:8080
Accept: */*
Content-Type: application/json
Content-Length: 5
Any idea or solution for this?
I also modified JQuery Source to set default values of the Headers sent by Ajax to JSON, but didnt work.
Seems like a same-origin policy issue. Using dataType='jsonp' should work, but this might require other changes.
See https://developer.mozilla.org/en/http_access_control for an in-depth explanation.
Actually, it was a cross Domain problem, I defined my URL as an IP, so the browser interpreted it like a Cross Domain request.
Thanks for everything!

Resources