Error when accessing localhost api in chrome net::ERR_INSECURE_RESPONSE - angularjs

I was trying to access api running in localhost using angular $resourses, chrome console gives me error saying ERR_INSECURE_RESPONSE.
I tried disabling web security in chrome. still same error. here is the angular factory that i used. How can I bypass this error and test my app.
ImpactPortal.factory('apiFactory', function ($resource) {
return $resource('https://localhost:8443/mifosng-provider/api/v1/client_impact_portal', {}, {
query: {
method: 'GET',
params: {},
isArray: true
}
})
});

Enabling CORS in Angular.js
var myApp = angular.module('myApp', [
'myAppApiService']);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
A server supporting CORS must respond to requests with several access control headers:
Access-Control-Allow-Origin: "*"
By default, CORS requests are not made with cookies. If the server includes this header, then we
can send cookies along with our request by setting the withCredentials option to true.
Access-Control-Allow-Credentials (optional)
If we set the withCredentials option in our request to true, but the server does not respond
with this header, then the request will fail and vice versa.

Only try this:
Go to https://[your-domain].com and then chrome block you with the famous page:
Your connection is not private
So go down to ADVANVCED and then proceed.
Your certificate is probably self-signed.
Remember to do that for each Chrome session.

You must authenticate first and then send each request along with the auth token.
I am using RestAngular so my settings might look a little different from what you are working on.
This will go in your application config :-
RestangularProvider.setDefaultHeaders({ 'X-Mifos-Platform-TenantId': 'default' });
and something like this will go in your controller/service
var login = Restangular.all('authentication?username=mifos&password=password').post().then(function(user) {
console.log(user);
}, function() {
console.log("There was an error saving");
});

Error 501 (net::ERR_INSECURE_RESPONSE) - 501 Not Implemented
The server either does not recognize the request method, or it lacks the ability to fulfill the request. Usually this implies future availability (e.g., a new feature of a web-service API).
Can you confirm that curl request is working fine
curl -k --user damien#email.com:password https://localhost:8443/mifosng-provider/api/v1/client_impact_portal
If it is working fine:
ImpactPortal.factory('apiFactory', function ($resource) {
return $resource('https://localhost:8443/mifosng-provider/api/v1/client_impact_portal', {}, {
query: {
method: 'JSONP',
params: {},
isArray: true
}
})
});
Try following this tutorial that consume an external API: http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app

Related

Enabling browser cookies with Swagger-js

I am using swagger-js/swagger-client (https://github.com/swagger-api/swagger-js) in an AngularJs SPA to send REST request to a nodeJS server using the TryItOut Executor.
I am using PassportJS for authentication. When I use Angular's $http service with the withCredentials property set to true:
$http({
method: 'GET',
withCredentials: true,
url: 'http://someUrl/someRestPath/' })
, everything works OK - browser cookies are properly set, and every further request is successfully authenticated.
Switching to swagger-js Executor, I cannot get authenticated properly since cookies are not being set. I have tried the following:
var swaggerClient = new SwaggerClient(specUrl)
.then(function (swaggerClient) {
swaggerClient.http.withCredentials = true; // this activates CORS, if necessary
as suggested in the documentation but this has no effect. Although I receive credentials when I authenticate with passport, further requests are unauthorized as cookies are not being set.
Left: cookies not being sent; Right: cookies being set
How to enable this behavior using swagger-js?
I was able to find a solution. The execute method of the Swagger-js client allows us to define our own http method. I simply used angular's $http service with the withCredentials set to true globally in the .config
import Swagger from 'swagger-client';
in .config:
angular.module('app', []).config(['$httpProvider',function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
And then when you create your swagger client:
Swagger({ url: 'some swagger specification (yaml/json)' }).then(client => {
client.execute({ http: $http, operationId: operationId, parameters: parameters});

Can not get response cookie from angular $http post using ionic

I am sending a post auth request from my localhost to a remote server to get response cookies returned by server(using ionic proxy to solve CORS). From chrome network inspector, I can see the response cookie has been returned from server. However, I am not able to access it from $http post response. I try almost everything from other posts and I still can not get the cookie. What I have tried
I use ngCookie and $timeout combination. Basically I get an empty object when I use $cookie.getAll() which I assume the cookie is not there
I also set withCredentials to true
I also tried headers.get('set-cookie')
My angular version is 1.5.3. Please help
Below is my code
angular.module('starter.controllers', ['ngCookies'])
.controller('DashCtrl', function($scope, $http, $cookies, $timeout) {
$http({
method: 'POST',
url: '/api/User/Authenticate',
data: {
Username: 'xxx',
Password: 'xxx'
},
withCredentials: true
}).then(function(response) {
$timeout(function() {
console.log($cookies); // return {}
console.log($cookies.getAll()); // return {}
});
}, function(response) {
});
})
Here is the server response

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

CORS workaround in Angular.js $HTTP POST?

Is there a workaround to sending POST request cross-domain via Angular, besides using a proxy? Below request is refused, ie: OPTIONS , net::ERR_CONNECTION_REFUSED It's just form data I want to submit to friend's local server for school project.
$scope.postJSON = function(){
var objJson = angular.toJson($scope.event);
console.log(angular.toJson($scope.event));
delete $http.defaults.headers.common['X-Requested-With'];
$http({
method: 'POST',
url: 'http://friendslocalserver.com',
data: objJson
}).success(function() {
console.log("POST Json object worked!");
}).error(function(){
console.log("POST Json object failed!");
});
}
You don't need to configure AngularJS for CORS. Your friend's server needs to support CORS requests and probably whitelist your domain. This depends heavily on the HTTP server used.

Web API loads via URL but get Error 404 from Angular script

I have a WebAPI method here:
http://localhost:50463/api/movies
and when accessing it from a browser it loads perfectly.
In my project (the same project as where Web API resides) when calling the method from AngularJS I get an error 500:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I click the link in the error it loads the data perfectly.
The routing for WebAPI is as follows:
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}",
new {action = "Get"},
new {httpMethod = new HttpMethodConstraint(HttpMethod.Get)}
);
This is the angular call
app.factory('dataFactory', function ($http) {
var factory = {};
factory.data = function (callback) {
$http.get('/api/movies').success(callback);
};
return factory;
});
I added this javascript just to rule-out angular, I get the same:
$.ajax({
url: "/api/movies",
type: 'GET',
//data: "{ 'ID': " + id + "}",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
Any idea what I have done wrong?
I assume your Web API and AngularJS app are running on a different port. In this case you are running in a Same-Origin-Policy issue.
Ensure your Web API is responding with HTTP CORS headers e.g.:
Access-Control-Allow-Origin: http://<angular_domain>:<angular_port>
or
Access-Control-Allow-Origin: *
Doesn't look like a CORS issue to me as you are using a relative URL in your $.ajax() request.
Did you try $.getJSON("/api/movies").then(successHandler, faulureHandler)
Not sure of that will help but for one you are sending a contentType header with a GET request which contains no content. There should be an Accept header instead, but WebAPI should be fine without one.
I would also remove the constrains from the routing and revert back to the default route mapping to see if the problem is there.
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional});

Resources