Getting Date from http header response - javascript

Okay so I can access the HTTP ajax response header using
xhr.getAllResponseHeaders();
but it doesn't seem to get the Date with it, though its there:
[Chrome]
**Response Header**
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:8092
Content-Type:application/json; charset=utf-8
**Date:Thu, 15 Jan 2015 16:30:13 GMT**
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
TotalCount:116
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
and the code only shows this :
[output on alert xhr.getAllResponseHeaders();]
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
here's the the ajax call:
$.ajax({
url: url,
type: "GET",
contentType: "application/json;charset=utf-8",
async: true,
success: function (data,status, xhr) {
displayNewData(data);
alert(xhr.getAllResponseHeaders());
},
error: function () {
alert(url);
}
});
Is there a way where I can get the Date in the response header?

It might be the case you are making a CORS request and the headers are filtered out for security reasons.
See also similar question about missing response headers in ajax request.
The solution might be to set this HTTP header in the server response:
Access-Control-Expose-Headers: Date

This Helped :
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
Accessing the web page's HTTP Headers in JavaScript

in your success method:
success: function (data,status, xhr) {
console.log(xhr.getResponseHeader('Date'));
},
If response is a success
res=xhr.getResponseHeader('Date');
if response fails
res=data.getResponseHeader('Date');

If you are using Nginx, you can put below code in Nginx config file:
add_header 'Access-Control-Expose-Headers' 'Date';
for real config example:
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Expose-Headers' 'Date';
root /usr/local/nginx/html;
index index.html index.htm;
}
After restarting your nginx service, you can call getAllResponseHeaders again and it will show you the "Date".

Related

Correctly use ajax to make a JSONP request - Error: Cross-Origin Read Blocking

Issue:
I'm trying to make a JSONP request using ajax, but I'm encountering the below error.
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://nftrade.com/_next/data/_Mat1YwGAWWtzBCNmnbbI/assets/avalanche/0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4/2493.json?chainName=avalanche&contractAddress=0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4&tokenID=2493&callback=jQuery341041842279918868885_1645936498754&_=1645936498755 with MIME type application/json.
The below URL works when I access the it using a chrome browser:
URL:
https://nftrade.com/_next/data/_Mat1YwGAWWtzBCNmnbbI/assets/avalanche/0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4/2493.json?chainName=avalanche&contractAddress=0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4&tokenID=2493
This is the response headers that is returned from the browser:
Response Headers
cache-control: private, no-cache, no-store, max-age=0,
must-revalidate
cf-cache-status: DYNAMIC
cf-ray: 6e3ec0558e647150-YUL
content-encoding: gzip
content-type: application/json
date: Sun, 27 Feb 2022 04:43:16 GMT
etag: "10f2-zWjggrplfqo/Q28tqHsMexHhykU"
expect-ct: max-age=604800,
report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
vary: Accept-Encoding
What I've tried and attempted:
The below is the code I'm currently using:
function getData() {
$.ajax({
url: `https://nftrade.com/_next/data/_Mat1YwGAWWtzBCNmnbbI/assets/avalanche/0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4/2493.json?chainName=avalanche&contractAddress=0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4&tokenID=2493`,
type: 'GET',
crossDomain: true,
dataType: "jsonp",
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
})
}
I've also used this ajax code but no luck:
function getData() {
var url = "https://nftrade.com/_next/data/_Mat1YwGAWWtzBCNmnbbI/assets/avalanche/0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4/2493.json?chainName=avalanche&contractAddress=0x2cca3a1a45c1b1036d7194cd15a981b8c2f9dee4&tokenID=2493";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "*/*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
I used reqbin's code to send an ajax request, which was successful. I'm starting to think it might be an issue with most browsers.
https://reqbin.com/req/nfilsyk5/get-request-example
Where am I going wrong? Can someone please shed some light? Thanks in advance.

Serverless CORS Error: Did not find method in CORS header ‘Access-Control-Allow-Methods'

I tried using Serverless framework and have followed the guide to enable CORS.
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
temperature: 30,
locationId: event.queryStringParameters || event.queryStringParameters.id
})
};
And I also added in the serverless.yml.
functions:
getListComment:
handler: handler.getListComment
events:
- http:
path: comments/list
method: get
cors: true
The final endpoint is here
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list
Somewhat when I tried calling the endpoint via AJAX.
$.ajax({
url: 'https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list',
type: 'json',
crossDomain: true,
contentType: "application/json",
success: function(data) {
alert('test');
}
});
There is nothing happens.
The Firefox console shows this message
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list.
(Reason: Did not find method in CORS header
‘Access-Control-Allow-Methods’).
And the Chrome console also shows this
XMLHttpRequest cannot load
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list.
Method JSON is not allowed by Access-Control-Allow-Methods in
preflight response.
But when I tried the endpoint in http://www.test-cors.org, it looks okay, though.
Sending GET request to https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list
Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: readystatechange
Fired XHR event: progress
Fired XHR event: readystatechange
Fired XHR event: load
XHR status: 200
XHR status text: OK
XHR exposed response headers:
Content-Type: application/json
Here's the response header for OPTIONS
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 0
Connection: keep-alive
Date: Sat, 17 Dec 2016 02:16:30 GMT
Access-Control-Allow-Headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
Access-Control-Allow-Methods: OPTIONS,GET
Access-Control-Allow-Origin: *
x-amzn-RequestId: d2ab4dce-c3fe-11e6-bcee-6767a7211424
X-Cache: Miss from cloudfront
Via: 1.1 c038088d4b94486d7346fd44d03188a0.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 30nHstKUhLwnHDwYEF3VdugR3JsuXHvUScBRDRFHRhimPW_DHS7RPQ==
Here's for the GET
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 158
Connection: keep-alive
Date: Sat, 17 Dec 2016 02:17:17 GMT
Access-Control-Allow-Methods: OPTIONS,GET
Access-Control-Allow-Origin: *
x-amzn-RequestId: ee6c19a6-c3fe-11e6-a0dc-01a17c495e09
X-Amzn-Trace-Id: Root=1-5854a02d-ba86e18abb4d47eb5094343b
X-Cache: Miss from cloudfront
Via: 1.1 18101d17be4ee51b5a03b68cfed50445.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 8K8NhwXGzhqR4bYLSFrRglogJQmQq3D3GJ2P4FrYoO-naDs-I55haA==
What did I do wrong?
You're making the request using a request method of 'json' (via the type property); 'json' is not a valid request method. Instead of type: 'json' you probably want dataType: 'json'.
The type property can be used to specify the request method (eg 'GET'), though it was deprecated in favour of the method property as of jquery v1.9.
$.ajax({
url: 'https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list',
method: 'GET', // not necessary since it will default to 'GET'
dataType: 'json', // use dataType, not type, to specify expected response data type
crossDomain: true,
contentType: "application/json",
success: function(data) {
alert('test');
}});

HTTP basic authentication works with jQuery POST request but not Angular

Update: Two things: One, I was issuing the POST requests for jQuery and Angular from two different domains. I created a jsfiddle to test both requests from the same domain, and they both work. I tried to make the fiddle pretty general so that you can swap out the config values and test an XML POST request with basic http authentication for any site that you need to. The other thing is that, using the Angular $http service, the Data-Type header results in the following error: Request header field Data-Type is not allowed by Access-Control-Allow-Headers in preflight response. So I removed that header. I'm still troubleshooting why the request is working from one domain and not the other. Once I figure that out, I'll update and mark as resolved. /update
The following jQuery POST request with basic authentication works as expected:
var mapstory = {
xml: '<?xml version="1.0" encoding="UTF-8"?> <wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" service="WFS" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd"> <wfs:Update xmlns:feature="http://www.geonode.org/" typeName="geonode:dja_remote_service_edit_test"><ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"><ogc:FeatureId fid="garbage_id" /></ogc:Filter></wfs:Update></wfs:Transaction>',
url: 'https://demo.mapstory.org/geoserver/wfs/WfsDispatcher',
auth: authToken //base64 encoded string of 'user:password'
};
$.ajax({
url: mapstory.url,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + mapstory.auth);
},
type: 'POST',
contentType: 'text/html',
dataType: 'xml',
processData: false,
data: mapstory.xml,
success: function(data) {
console.log(data);
}
});
Here are the response headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin,Content-Type,Accept, Authorization, x-requested-with
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Connection: keep-alive
Content-Length: 0
Date: Fri, 01 Jul 2016 21:06:50 GMT
Server: nginx
access-control-allow-origin: http://localhost:8888
However, the following in AngularJS (v1.2.21) doesn't work:
var mapstory = {
xml: '<?xml version="1.0" encoding="UTF-8"?> <wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" service="WFS" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd"> <wfs:Update xmlns:feature="http://www.geonode.org/" typeName="geonode:dja_remote_service_edit_test"><ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"><ogc:FeatureId fid="garbage_id" /></ogc:Filter></wfs:Update></wfs:Transaction>',
url: 'https://demo.mapstory.org/geoserver/wfs/WfsDispatcher',
auth: authToken //base64 encoded string of 'user:password'
};
var config = {
withCredentials: true
};
config.headers = {
'Authorization': 'Basic ' + mapstory.auth,
'Content-Type': 'text/html',
'Data-Type': 'xml'
};
$http.post(mapstory.url, mapstory.xml, config)
.success(function(data) {
console.log(data);
});
I receive the following response headers from this request:
Content-Language: en
Content-Type: text/xml;charset=UTF-8
Date: Fri, 01 Jul 2016 20:52:13 GMT
Server: WSGIServer/0.1 Python/2.7.11
Vary: Accept-Language, Cookie
X-Frame-Options: SAMEORIGIN
I get a valid XML response from the Angular request above, but the response indicates that the request wasn't authorized.
I tried swapping out the Content-Type value with application/xml, but this didn't have any effect on the result.
I've read through the Angular $http documentation and approached a number of other resources, such as this Stack Overflow question which describes a similar issue. A recommended solution is to remove the X-Requested-With default header. This step is apparently not necessary in Angular versions above 1.2 (here's a closed issue for that on Angular's Github), but I tried it anyhow. No luck.
Any guidance on this would be wonderful. Thank you very much for taking the time to read and consider this!
It looks like the server does not recognize angular as a same domain application. So what you must do is to include in the web server headers the value: access-control-allow-origin: * to allow requests from "outside" domains.

Why is successful jQuery cross domain post request not firing success handler?

I am making the following JQuery cross domain ajax post request from a phonegap (appgyver steroids) app.
function do_something(callback_method, some_vars)
{
var stringified_some_vars = JSON.stringify(some_vars);
$.ajax({
type: "POST",
url:"http://www.somedomain.com/endpoint",
data: {'some_vars' : stringified_some_vars},
async: true,
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(result)
{
var myObject = $.parseJSON(result);
callback_method(myObject);
},
error: function(fail)
{
supersonic.logger.debug(fail);
}
});
}
The post request is successfully sent to the server (Google Appengine - Python) - i.e. the server fires the relevant method. However, when the server response is received the jQuery Ajax method doesn't fire the success handler - it instead fires the error handler. The error text prints to console as
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
The headers in the json response from the server are as follows:
Content-Length: 0
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Content-Type: application/json
the content of the response is as expected. and is written using
text_to_send = json.dumps(python_dict)
self.response.headers.add_header('Access-Control-Allow-Origin', '*')
self.response.headers['Content-Type'] = 'application/json'
self.response.write(text_to_send)
It's not clear to me where this error is coming from. Allowing cross domain requests doesn't seem to have fixed the issue. jsonp GET requests work fine - but obviously these aren't allowed for POST requests. Could anyone tell me where I'm going wrong?
Edit 1
Following the suggestion of #Faisal I adjusted the server code as follows
from urlparse import urlparse
uri = urlparse(self.request.referer)
origin = '{}://{}'.format(uri.scheme, uri.netloc)
self.response.headers.add_header('Access-Control-Allow-Origin', origin)
self.response.headers['Content-Type'] = 'application/json'
The headers are now
Content-Length: 0
Cache-Control: no-cache
Access-Control-Allow-Origin: http://localhost
Content-Type: application/json
However the same error is encountered
I think if it's withCredentials: true you need your origin to be exact match instead of wildcard (*). Here is a quick code to get it from referer. But you should probably also check if its one of the allowed origins:
from urlparse import urlparse
uri = urlparse(self.request.referer)
origin = '{}://{}'.format(uri.scheme, uri.netloc)
Edit
Try adding:
self.response.headers.add_header('Access-Control-Allow-Credentials', 'true')

cross-origin resource sharing (CORS) with jQuery and Tornado

Let's say, I have a Tornado web server (localhost) and a web page (othermachine.com), and the latter contains javascript that needs to make cross-domain ajax calls to the Tornado server.
So I set up my Tornado as such:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
self.set_header("Access-Control-Allow-Credentials", "true")
self.set_header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
self.set_header("Access-Control-Allow-Headers",
"Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control")
And my javascript makes a jQuery call:
$.ajax({
type: 'GET',
url: "http://localhost:8899/load/space",
data: { src: "dH8b" },
success: function(resp){
console.log("ajax response: "+resp);
},
dataType: 'json',
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.setRequestHeader('Access-Control-Request-Method', 'GET');
xhr.setRequestHeader('Access-Control-Request-Headers', 'X-Requested-With');
xhr.withCredentials = true;
}
});
But I get the lovely XMLHttpRequest cannot load http://localhost:8899/load/space?src=dH8b. Origin http://www.othermachine.com is not allowed by Access-Control-Allow-Origin error. I can't tell which side of jQuery / Tornado (or both?) am I not setting up correctly.
According to dev tools, these are the headers the jQuery request is sending:
Request Headers
Accept:*/*
Origin:http://www.othermachine.com
Referer:http://www.othermachine.com/athletes.html?src=BCYQ&msgid=6xjb
User-Agent:Mozilla/5.0 ...
If I simply make a request from my browser's url field I get a '200 OK' with this:
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, User-Agent, X-Requested-With, X-Requested-By, Cache-Control
Access-Control-Allow-Methods:GET,POST
Access-Control-Allow-Origin:http://www.othermachine.com
Content-Length:0
Content-Type:text/html; charset=UTF-8
Server:TornadoServer/2.2.1
Does that mean Tornado is doing its job? I tried to follow the advice of all the stackoverflow CORS+jQuery posts (e.g. this), to no avail. CORS in concept seems simple enough, but maybe I am fundamentally misunderstanding what is supposed to happen in a CORS transaction... please help! Thanks in advance.
Nevermind, coding too late and too long causes one to trip over things the size of typos. For the record, this is all you need for jQuery:
var data = { msgid: "dH8b" },
url = "http://localhost:8899/load" + '?' + $.param(data);
$.getJSON( url, function(resp){
console.log("ajax response: "+resp+" json="+JSON.stringify(resp));
});
And this is all you need for Tornado:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
Using jQuery 1.7.2, Tornado 2.2.1.
try setting origin to be: othermachine.com. it should be a domain name, not a website address

Categories

Resources