Set-Cookie header not setting cookie in Chrome - javascript

I'm AJAXing a call to a another services API, which is then supposed to return a cookie that will be set in my browser to allow me to make the rest of my API calls.
However, while the response headers include a 'Set-Cookie' header, no cookie is ever actually set. I'm using Google Chrome.
Here is the Response Headers:
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:keep-alive
Content-Encoding:gzip
Content-Length:37
Content-Type:application/json
Date:Thu, 25 Jun 2015 18:27:37 GMT
Expires:Thu, 25 Jun 2015 18:27:36 GMT
Server:nginx/1.4.6 (Ubuntu)
Set-Cookie:sessionid=67cb9796aa794a4975b28876ea6dd3d5; expires=Thu, 09-Jul-2015 18:27:37 GMT; httponly; Max-Age=1209600; Path=/
Vary:Cookie
And here is the AJAX call:
$.ajax({
type: "POST",
crossDomain: true,
contentType: 'text/plain',
data: data,
url: urlhere
success: function(result, status, xhr){
console.log('hi');
console.log(xhr.getAllResponseHeaders());
},
error: function(xhr){
console.log(xhr.status);
console.log(xhr.statusText);
}
});
The Chrome resources page also shows that no cookie is being set. Any and all help would be greatly appreciated!

You need to append withCredentials to your XHR call, this answer shows how to do that with jQuery. https://stackoverflow.com/a/7190487
Without that additional flag, the browser will not accept a set-cookie header.

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.

Getting Date from http header response

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

How to access ETag header with jQuery AJAX request?

I'm using a jQuery ajax call to request data from a server that is sending an ETag in the HTTP response headers. I need access to the header, but when the request succeeds and I call jqXHR.getAllResponseHeaders(), I only see a subset of the headers returned by the server.
Example:
var jqXHR = $.ajax({
type: 'GET',
url: <my api url>,
dataType: 'json',
ifModified: true,
success: function (result) {
var headers = jqXHR.getAllResponseHeaders();
console.log(JSON.stringify(headers));
});
The headers I see from the jqxhr are:
Pragma: no-cache\r\n
Last-Modified: Wed, 22 Jan 2014 10:45:14 +0000\r\n
Content-Type: text/html\r\n
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, no-cache=\"set-cookie\"\r\n
Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n
The actual headers returned from the server (observed in chrome dev tools):
Access-Control-Allow-Origin:*
Cache-Control:no-cache="set-cookie"
Cache-Control:post-check=0, pre-check=0
Cache-Control:no-store, no-cache, must-revalidate
Connection:keep-alive
Content-Encoding:gzip
Content-Length:407
Content-Type:text/html
Date:Fri, 24 Jan 2014 20:27:54 GMT
ETag:"29d8d1d98115057fe902b520199ea1b3"
Expires:Sat, 26 Jul 1997 05:00:00 GMT
Last-Modified:Thu, 23 Jan 2014 07:14:57 +0000
Pragma:no-cache
Server:nginx/1.1.19
Set-Cookie:AWSELB=F3E9557318EB956CA386FC6CB4270164AD7830493699A2B6AED008F4C5F9DB5952A2A1072C33DDC32DEDE0CA6A3734EBAFD51B57A7A093B69A36A6659EF493E1B92BA63DE6;PATH=/
X-Powered-By:PHP/5.4.19
I need to access the ETag header, but it seems as if jQuery or chrome are hiding it from me. I have tried the same code in Firefox with the same results. Can someone help me with this?
You can try accessing headers in complete callback instead of success
complete: function(XMLHttpRequest, textStatus){
var eTag = XMLHttpRequest.getResponseHeader('ETag');
}
This seems to work for some users here
This could be a CORS issue. I was having the same problem, I saw the headers in Chrome - however my code could not access it.
I have ASP.Net Web API for my back-end and under the <system.webServer> node had to add:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers" value="ETag, Retry-After"/>
</customHeaders>
</httpProtocol>
I realized this after reading the following post:
Etag header not returned from jQuery.ajax() cross-origin XHR

JQuery AjaxComplete Method Stripping Out Custom Headers?

I am trying to follow option #3 in the solution at this SO post: A controller action which returns a partial view inserts the logon page when authorization fails
I'm running into a problem reading my custom header in the ajaxComplete method in jquery.
I have confirmed in fiddler and in chrome's debug tools that the custom header is in fact being sent back and received by the browser...
Response Headers (in Fiddler):
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 15 Jan 2012 04:00:13 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Unauthorized: 1
Cache-Control: private
Content-Length: 0
Connection: Close
Response Headers (as received by Chrome):
Cache-Control:private
Connection:Close
Content-Length:0
Date:Sun, 15 Jan 2012 04:12:13 GMT
Server:ASP.NET Development Server/10.0.0.0
Unauthorized:1
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
Response Headers (as found from calling "getAllResponseHeaders()" on the xmlHttpRequest variable passed into ajaxComplete):
Date: Sun, 15 Jan 2012 04:42:21 GMT
X-AspNet-Version: 4.0.30319
Connection: Close
Content-Length: 65
X-AspNetMvc-Version: 3.0
Server: ASP.NET Development Server/10.0.0.0
Content-Type: application/json; charset=utf-8
Cache-Control: private
Interestingly, the function that is called upon the return of the original ajax request (as initiated by jquery) does receive the Unauthorized header.
Does anyone know what's going on here and what I can do to solve this issue?
Here's my "ajaxComplete" javascript code
$(document).ajaxComplete(function (event, request, settings) {
alert(request.getResponseHeader('Unauthorized'));
});
You can take a look here. It might be helpful if you are using the same plugin (ajaxmanager) on your page. If not, check your other plugins.
Vucetica's initial response got me thinking and I spent the last hour looking through jquery's code. I have my custom header coming back now. It looks like the trouble stemmed from an unhandled exception in my code within the success callback of the original ajax request.
Definitely something I should fix, but it seems odd that jquery would allow itself to be susceptible to that in a way that it fails silently and only affecting the custom headers. This unexpected behavior really led me in the wrong direction initially.
Anyway, thanks for your help everyone.
For completeness sake, here is my code before and after.
Before (no custom headers received in the ajaxComplete method)
$.ajax({
type: "GET",
url: "/Game/GetPlay/27?roundId=" + that.gameState.RoundToDisplay,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (play, request, settings) {
that.play = play;
that.startGame();
},
error: null,
cache: false
});
After (working)
$.ajax({
type: "GET",
url: "/Game/GetPlay/27?roundId=" + that.gameState.RoundToDisplay,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (play, request, settings) {
that.play = play;
try {
that.startGame();
} catch(err){
}
},
error: null,
cache: false
});

Ajax call to web service - success in method but forbids data access

I am trying to call a web service from an ajax jquery. It is successfully entering the success method but unfortunately a 403 error is being triggered and thus won't allow me to access the data.
This is my code:
try {
$.ajax({
type: "POST",
url: urlAddress,
data: dataa,
contentType: "text/xml; charset=utf-8",
success: function(Msg) {
// $("#Result").text(msg.d);
alert("ok");
alert("hi "+Msg.responseText + " How are you?");
},
error: function(request, status, error) {
alert("Error "+request.statusText.toString());
alert("ERROR");
}
});
}
catch (e)
{}
Msg.ResponseText comes back "undefined"
From Live Http Headers I get the following:
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
Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115 Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
HTTP/1.1 403 Forbidden
Content-Length:1758
Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Tue, 27 Jul 2010 10:59:04 GMT
Smells like urlAddress is not located on the same domain you're running that script.
That would breach the same origin policy and therefore, fail.
If I'm wrong here with that assumption, your're webservice might require a login (username+password) which you might missing to pass through .ajax().

Categories

Resources