Angular post failing in Chrome - angularjs

I have the following
function quoteGridController($scope, $http) {
$http.defaults.useXDomain = true;
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
delete $http.defaults.headers.common['X-Requested-With'];
$http.post("http://localhost:57048/service/Quote/ReadQuoteForClientId", $.param({ "ClientId": 2 }))
.success(function (data, status) {
alert("Success");
$scope.status = status;
$scope.data = data;
})
.error(function (data, status) {
alert("Error");
$scope.status = status;
$scope.data = data;
});
}
This call fails when using Chrome but succeeds when using Internet Explorer. From what I have read this is a CORS problem. Is there any way I can get this call to work with both browsers?
EDIT: The Chrome console is giving me the following
XMLHttpRequest cannot load. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Therefore not allowed
access.

As mentioned in the comments above, this is not a client side issue. Chrome do not allow CORS when running from your localhost. A possible solution is to run your web API using a custom domain domain name as explained here.
I however took the easy route and started Chrome with web security disabled, just so that I can test my web API code. Run this from the command prompt
chrome.exe --disable-web-security
Then run your application

Related

Angular http.get + WebApi = Cors failure

on server side I have a C# web api including a controller attributed like this on class level:
[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]
I can make ajax calls, e.g. form localhost just fine.
Now I am starting with AngularJS and the http.get-method fails with the following message:
XMLHttpRequest cannot load http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my AngularJS code:
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function($scope, $http) {
var onSuccess = function(data, status, headers, config) {
$scope.data = data;
};
var onError = function(data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");
promise.success(onSuccess);
promise.error(onError);
});
</script>
In Fiddler, I can see, that the header of the AngularJS-HTTP-Get request has an "Origin: null" entry, which seems to be related to the problem. I think, if instead "null" the value would be "http://localhost", it should work.
Can anyone help me out?
Thank you!
Could it be because in your [EnableCors] attribute, you need to change headers: "", methods: "" to headers: "*", methods: "*"?
Also, you should not include a forward slash at the end of the origins url (if you did).
We had the same issue in our project and we tried so many options as per the suggestions from various web sites. But the thing that worked/working in our case is writing custom CORS provider as mentioned here.
Upppps!
When running in the fresh air today I suddenly was aware why Origin was null. It was, because I was not calling the web site in IIS, but instead I opened the file directly in the file system. For sure, there was no valid URL when doing so, and the Origin was null for the web server.

unable_to_verify_leaf_signature when posting from AngularJs/Cordova

I'm running into the following error when trying to post to my identityserver using "https://localhost:44333/identity/connect/token" from my angularjs authService, but when I post from Postman or Fiddler all works fine.
I have self created a certificate which I imported and so when I navigate to https://localhost:44333/identity in my browser all is good.
What I could gather from googling around was that it had something to do with certificates, but I can only find topics on node.js. I'm trying to authenticate from a angularjs service to an IdentityServer3 which I selfhosted on the above url using owin.
The following is what my angulajs login code looks like:
var _login = function (credentials) {
var user = { grant_type: 'password', username: credentials.userName, password: credentials.password, scope: 'salesApi' }
var urlEncodedUrl = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64Encoded
};
console.log(base64Encoded);
$http.post(serviceBase + 'connect/token', { headers: urlEncodedUrl }, { data: user }).success(function (data, status, headers, config) {
localStorageService.set('authorizationData', { bearerToken: data.access_token, userName: credentials.userName });
_authentication.isAuth = true;
_authentication.userName = credentials.userName;
_authentication.bearerToken = data.access_token;
}).error(function (err, status) {
console.log(err);
_logOut();
});
};
Any ideas on what I'm missing or how to solve this error?
UPDATE: Is this actually a ripple emulator or cordova issue?
If anyone is still having the same issue, it may be worth trying my Ripple solution at Using the Apache Ripple emulator with a self signed SSL certificate
I'll add the steps of my answer from the above SO question to prevent further downvotes:
Create a shortcut to run Chrome with the --disable-web-security flag set. If further information is required see my answer at Visual Studio, Ripple Emulator and CORS/Cross Domain Ajax
Start Ripple using either the command line or Visual Studio
Start an instance of Chrome using the shortcut from 1.
Browse to your Ripple url and issue your request over HTTPS
This will fail and the dev tools console will show POST https://mydomain:port/api_endpoint net::ERR_INSECURE_RESPONSE
In a new tab browse to your https://mydomain:port url
This will result in a "Your connection is not private" web page. Click on "Advanced", and then on "Proceed to https://mydomain:port (unsafe)" to accept the self signed SSL
Now back on the Ripple tab try issuing your request again and it should succeed.
I had the same problem and resolved get API to work with a real host. Seems to be a issue with Ripple.

Requesting data to Sharepoint 2013 using rest api service to integrate with angular app

I am learning sharepoint 2013 for a required incoming project. I has never worked on .net or any other ms technology so i would appreciate if the answers are dumb proof.
I have a server that is running sharepoint 2013 and iis v8.0
Currently i am having some issues, but the main one is that i am trying to access the api service from an angular application. I setted the mapping for intranet to the ip of the server and i can access the api through to the web browser.
I also setted the http response headers to "Access-Control-Allow-Origin" : * in iis. However when i try to access the api using the angular $http object i am getting a message that says XMLHttpRequest cannot load http://x.x.x.x/_api/web. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost : 9000' is therefore not allowed access. The response had HTTP status code 401.
The idea is that the angular application is totally independant of sharepoint and any .net technology. All i want to do is use the rest api to get/edit data.
The request i am making looks like this:
angular.module('angYeoman2App')
.factory('SharePointJSOMFactory', function SharePointJSOMFactory($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
SharePointJSOMFactory.getTasksRESTAppWeb = function() {
var restQueryUrl = "http://x.x.x.x/_api/web";
$http({
headers: { 'Accept': 'application/json; odata=verbose' },
method: 'GET',
url: restQueryUrl
})
.success(function(data, status, headers, config){
console.log(data);
deffered.resolve();
})
.error(function(data, status, headers, config){
console.log('error', data)
deffered.resolve();
});
return deffered.promise;
};
SharePointJSOMFactory.data = function() {
return data;
};
return SharePointJSOMFactory;
});
Any idea what i am doing wrong? I has read that i need to add <% Response.AddHeader("Access-Control-Allow-Origin", "*") %> somewhere, but i don't have any idea to what file.
I also have another problem (not so relevant at this point): When i try to access to a subsite using the ip address it seems it is applying the theme of the parent and it doesn't load the content of the subsite. Any idea why?
Any help is welcome. Tks for your time, have a nice day.

angularjs $http post not working with Chrome browser

I'm trying to post an object to my rest service using angularjs.
Unfortunately it isn't working with Google's Chrome browser. Firefox and Internet Explorer work perfectly fine!
Does anyone have an idea what could be the problem?
Heres my Frontend -call:
$scope.saveAssignment = function (cap, aId, wId, hId) {
//all the parameters are strings
var postData = {
assignmentId: aId,
status: "CLOSED",
startDate: new Date(),
endDate: new Date(),
captionText: cap,
workerId: wId,
segment_Id: hId
};
var header ={
'Content-Type': 'application/json; charset=utf-8'
};
$http.post("https://localhost:8443/rest/v1/saveAssignment", postData, header)
.success(function (data, status, headers, config) {
console.log("IN SAVE ASSIGNMENTS - SUCCESS");
console.log(status);
})
.error(function (data, status, headers, config) {
console.log("ERROR!");
//As a response I get data = '' and status = 0
})
}
I have the same problem if I deploy it (independent of localhost or not).
On the server-side (JPA), I'm accepting the call with:
#Path("saveAssignment")
public class SaveAssignment{
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response saveAss(String assJson) {
System.out.println("TEST");
......
......
}
But not even the print statement "TEST" gets executed...
UPDATE
It looks like it has to be a CORS issue...
Chrome is only sending an OPTION request instead of an POST...
Idea how to fix this?
I already tried
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
but without succes... :(
UPDATE 2
Unfortunately I still don't manage to get it working. So I did a workaround by consciously excluding users with a Chrome browser from doing this post on my page (i.e. seeing the entire page)... (I used it for Amazon's Mechanical Turk, so it's not that severe). But it's not a solution for the origin problem... :-(
To exclude users with Google's Chrome browser I added the following:
$scope.chrome;
$scope.setIsChrome = function(){
var chromium = window.chrome;
var vendorName = window.navigator.vendor;
if(chromium !== null && vendorName === "Google Inc.") {
$scope.chrome = true;
} else {
$scope.chrome = false;
}
}
You have to check additionaly for the vendor name, since the Opera browser return true for "window.chrome" as well...
Is your angular app served via same HTTPS server? If localhost:8433 has self-signed or not matching certificate then that may be your problem as Chrome usually displays security exception page in such case.
Just open any URL starting with https://localhost:8443/ as normal page an then confirm security exceptions. That should help.
Update:
If you use iframe then the embedded page may be restricted by sandbox: http://msdn.microsoft.com/en-us/hh563496.aspx

Getting JSON data using Angular JS's $http service

I need to get JSON data from a server with URL :
http://xxxx.xxxx.xxxx.xxxx:8084/inpulse/api/user/listall
Here's my angular code:
var app = angular.module('app',[]);
app.controller('Controller', function ($scope,$http) {
$scope.email="";
$scope.password="";
$scope.sample="";
$http({
method: 'GET',
url: 'http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall',
})
.success(function (data, status, headers, config) {
var ret = data;
$scope.sample = JSON.stringify(ret);
})
.error(function (data, status, headers, config) {
alert(status);
// something went wrong :(
});
});
Now the same code worked when i used a JSON test URL like http://ip.jsontest.com/.
Its Definitely not a problem with the server because I tested it with a REST client and got a response. I can't figure out what I'm doing wrong.
It might be a CORS configuration issue.
If you are trying to access the server from a page that is not in the same domain/origin, you'll get an error because the server is not configured to allow CORS.
The error reported by Chrome looks like this:
XMLHttpRequest cannot load http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Other than that the code seems to work just as expected.

Resources