angularjs $http post not working with Chrome browser - angularjs

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

Related

AWS S3: No 'Access-Control-Allow-Origin' header is present on the requested resource

In my angular app, I have the following error when I try to make an REST api.
My Code is given below:
Angular Controller
$scope.saveTeam = function() {
var club = {};
club.name = $scope.selectedClub;
var service = API.getService();
service.create( {}, { club: club },
function( res ) {
}, function(err) {
console.log("club err : ", err);
});
}
}
Angular Factory
// Clubs service used for communicating with the coaches REST endpoint
angular
.module('app')
.factory('API', ['$resource', 'session', function($resource, session) {
var mainUrl = '/clubs';
return {
getService : function() {
var token = session.getToken();
return $resource(mainUrl, { }, {
createClub: {
method: 'POST',
url: mainUrl,
isArray: false,
headers: { 'Token': token }
}
})
}
}
});
How can I solve this error? Thanks in Advance.
Install this chrome extension to avoid CORS error. This error generally comes because of the security headers in the request made by a client. Use the line of code shown below before making any request to server.
$http.defaults.headers.post["Content-Type"] = "application/json";
Working principles of CORS is a simple HEADERS game between Client and Server. The browser (the client) set in the Origin key the current domain in your case set "http://localhost:9001". The server, in turn, verified that this value is among those trusted and responds with another piece of information (always in the header) with the key Access-Control-Allow-Origin. If the two values are equal, then the browser uses the response, otherwise you will have an error.
So in the future you need to configure the server but for development you can start the Chrome browser with Disable same origin policy. With disable security the browser don't set the origin and you don't have a problem. This is the problem so check this link:
Disable same origin policy in Chrome

Angular Resource POST Request adding extra quote in JSON request

Let me start off by saying that this issue is not happening in Chrome. I have been really only testing in Chrome but then I decided to try it out in Firefox only to find I can't log in because my JSON request is not right.
Here's my call:
self.user = $resource('http://my-site.com/a/account/login', {}, {
login : {
method: 'POST'
},
.
.
.
self.user.login({username: username, password: password}).$promise.then(function(response) {
self.model.loggedInUser = response;
deferred.resolve(self.model.loggedInUser);
}).catch(function(err) {
self.model.loggedInUser = undefined;
deferred.reject(err);
});
I'll also mention that I have an Interceptor set up, but for this specific call all it does is the following:
'request' : function(config) {
var deferred = $q.defer();
deferred.resolve(config);
return deferred.promise;
}
So if I look in the Chrome network tab I see something like this:
{"username":"myName","password":"173A9F67AB4399D34561D96BFDB0E3B009C39232"}
Nothing out of the ordinary there.
However, this is what I see in Firefox:
{"username":""myName","password":"173A9F67AB4399D34561D96BFDB0E3B009C39232"}"
Notice the extra quotation mark after the colon and after the ending curly brace. This is not right. I can't seem to figure out what is causing this though. Espeically why it only seems to be happening in Firefox (only 2 browsers I've tried are Chrome and Firefox).
Edit: Thinking this could be useful, the Content-Type of my request is the same in both browsers:
application/json; charset=utf-8

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.

Angular post failing in Chrome

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

Resources