I am trying to create a cross domain request but I am getting
XMLHttpRequest cannot load [domain]/page.aspx?callback=jQuery1510773820479400456_1319466915384&_=1319466916554. Origin [domain] is not allowed by Access-Control-Allow-Origin.
here is how I make the call
$.ajax({
url: "domain/page.aspx?callback=?",
dataType: 'jsonp',
processData: false,
success: function (data) {
/*
* do something
*/
}
})
Nn server side I add the headers
Response.AppendHeader("Access-Control-Allow-Origin", "[domain]");
//I also tried Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
Am I missing something?
Thanks
Related
When I make CORS request from 127.0.0.1:
return jQuery.ajax({
'type': 'GET',
'url': url,
xhrFields: {
withCredentials: true
},
ContentType: 'application/json',
});
Then everything is OK:
But when I change first letter of ContentType to lowercase as next:
return jQuery.ajax({
'type': 'GET',
'url': url,
xhrFields: {
withCredentials: true
},
contentType: 'application/json',
});
Then request is failed:
I suppose that nginx compares headers case sensitively.
Is this a case? or something different happened... =(
The point is that your browser doesn't send Content-Type: application/json in the second case. The NGINX isn't involved in that at all, your browser sends the Content-Type in both cases, but when you give the ContentType parameter to jQuery, it's being silently ignored. The correct parameter is contentType, not ContentType.
i got a problem in meteor when i try to make a cross origin call.
when i make the call using Ajax.
$.ajax({
type: 'GET',
url: signoutUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
console.log('success');
},
error: function (e) {
console.log('error in HTTP :: >>>>' + JSON.stringify(e));
}
});
it works fine with no problem. but when i am using meteor's HTTP.call method for the same Http request it sent me the error.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
i set the parameters and header in meteor Http.call are
HTTP.call(method, URL,
{params: {
async: false,
contentType: "application/json",
dataType: 'jsonp'},
headers:{'Access-Control-Allow-Origin':'https://www.google.com/*'}
}, function (err, result) {}
but when i check the request. i found the header is like
access-control-request-headers:access-control-allow-origin
so, help me where i am wrong in this HTTP request and how to resolve it
I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service and CORS limitations. I think I just need to get my headers right. Do I also need to tweak my server config?
I am getting the following error:
XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control- Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.
My Service
app.service('Auth', function($http) {
var headers = {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
return $http({
method: "POST",
headers: headers,
url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
data: {"email":"my#email.com","password":"secret"}
}).success(function(result) {
console.log("Auth.signin.success!")
console.log(result);
}).error(function(data, status, headers, config) {
console.log("Auth.signin.error!")
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
});
App Config
var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: http://enable-cors.org/server.html
I can successfully make the AJAX call to my service with the following code:
var serverData = { "ZoneParent": "123" };
var request = $.ajax({
type: "POST",
url: "/./Services/Reports.svc/getZones",
contentType: "application/json",
dataType: "json",
jsonp: null,
jsonpCallback: null,
data: JSON.stringify(serverData)
});
request.done(function (msg) {
alert(JSON.stringify(msg));
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
However, when I try to implement the same call with my Kendo grid I get an error
The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'
for getZones. My service call work fine with DataTables, but I want to switch to Kendo potentially. I have messed with this for days to no avail. The application is not MVC. Here is my Kendo code snippet:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "JSON",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
schema: {
data: "d"
}
});
var grid = $("#allGrids").kendoGrid({
dataSource: dataSource,
height: 200
});
As cfeduke made similar suggestion you can try to add contentType to the read object of the transport read config just as you did in the $.ajax call.
e.g.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "json",
contentType: "application/json",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
It sounds like the server's reply "Content-type" header is something other than the expected "application/json".
You can use cURL:
curl -v -H "Content-type:application/json" -H "Accept:application/json" \
http://localhost/Services/Reports.svc/getZones
to invoke the endpoint and check the returned header values (-v is verbose, you won't see the headers without it).
Sometimes just setting an "Accept: application/json" header is enough to reveal the problem - either the server coerces the output into JSON or it throws an error that can be tracked down.
I am investigating if there is a another way around this. But seems like Kendo has many limitations and this is one of them. Datables doesn't need a header, just the JSON format.
This is what you need to add to your controller that is sending the data (in case its ajax call)
header("Content-type: application/json");
I wish it wouldn't be like this but Kendo forces this I believe. I prefer datatables, much more freedom and you can customize more.
On login I want to generate a new SessionId. I have found one solution that works, but it requires some pretty hackish things and requires the app have Full Trust securityPolicy setting.
Is there any other way to achieve this?
Looks like this works:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
By clearing out that cookie, a new session with a new session ID will be created at the server.
(Reference: Microsoft Support)
EDIT: Here's an example using AJAX (with jQuery) to call the server code without a page refresh - it calls twice, once to remove the first session, and once to generate a new one. There may be a better way, but this does work.
function newSession() {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/ClearSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/NewSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("Success!"); },
error: function (x, y, z) {
console.log("Failure!");
}
});
},
error: function (x, y, z) {
console.log("Failure!");
}
});
}
And on the code-behind (for WebForms - you could also do this with an MVC controller):
[WebMethod]
public static void ClearSession()
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
[WebMethod]
public static void NewSession()
{
HttpContext.Current.Session["x"] = 123;
}
I'm currently considering a configuration-based solution, rather than a code-based one. I would configure either the web server or load balancer to strip away request and response headers containing cookies for just the login page. Remove the "cookie" headers for request headers and "set-cookie" for response headers.
Every request (GET or POST) to the login page will contain no cookie information, thus forcing ASP.NET to create a new session and (more importantly) a new session id.
It's less efficient than forcing a new session creation on login, but the technique could be useful in cases where you cannot modify the code.