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
});
Related
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');
}});
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.
I have a HighCharts client whose responsibility is to load data from a webservice and show a chart. The function that requests data looks as below:
function requestData() {
$.ajax({
url: 'http://myhost.com/type?x=1&y=2&z=3',
headers: {
Accept : "application/json"
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}
(in the future, the url property will be dynamically generated)
The target webservice is read-only and implemented using Flask microframework: its purpose is to return JSON data to the HighCharts client. This is the Flask view (function) taking care of data requests:
#app.route('/<type>')
def get_data(type):
x = request.args.get('x','')
y = request.args.get('y','')
z = request.args.get('z','')
[...]
Problem: when I execute the javascript code in Chrome, the following HTTP request is sent to the webservice:
GET /type?x=1&y=2&z=3 HTTP/1.1 // '&' have been escaped to '&'
Host: myhost.com
Connection: keep-alive
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Accept: application/json
Referer: http://myhost.com/chart.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
...I get a 404 status code (Bad Request) from the server, which is perfectly good and expected whenever one or more of the request's query parameters is null or malformed:
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html; charset=utf-8
Content-Length: 16
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Wed, 14 Nov 2012 10:23:49 GMT
After debugging on my Flask webservice I noticed that only the x query parameter (which please note is the first given in the HTTP request) is correctly parsed, while y and z are empy strings, which causes the 404.
Why is it happening? Any charset inconsistency regarding the & -> & escaping?
Thanks, any hint would be of real help (just ask if you need more specs or code)
I think the error is as you expected the escaped ampersand.
Try this:
function requestData() {
$.ajax({
url: 'http://myhost.com/type',
headers: {
Accept : "application/json"
},
data: {
x: 1,
y: 2,
z: 3
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}
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().
im currently setting up asp.net to accept DELETE http verb in the application.
However, when i send
"DELETE /posts/delete/1"
i always get a 405 Method not allow error. I tried to take a look at the header:
Response Headers
Cache-Control private
Pragma No-Cache
Allow GET, HEAD, OPTIONS, TRACE
Content-Type text/html; charset=utf-8
Server Microsoft-IIS/7.5, Private-Server
Date Tue, 17 Nov 2009 18:30:31 GMT
Content-Length 5590
Allow GET, HEAD, OPTIONS, TRACE
notice the Allow header in IIS7, it's only allow GET HEAD OPTIONS and TRACE. I currently using [AcceptVerbs(HttpVerbs.Delete)] in my delete controller (i think this one is extended by MVCContrib, correct me if im wrong)
PS: i send DELETE using Javascript:
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
and:
_ajax_request($(this).attr('href'), "", function(d) { alert("submit"); }, "json", 'DELETE');
THank you in advance!
MVC 2 has this built in. You don't need MVCContrib for it. See HtmlHelper.HttpMethodOverride and HttpDelete.