AngularJS $http request to Web Service requires CORS - angularjs

I am writing a service which needs to access a WebService (which I have no control over) - an API which I would like to consume in my application. I have visited the url in question within my browser and the login is successful, and I can see my access token, however when I try to use $http to visit the same page I get errors in the developer console in IE.
angular.module("app").factory("MyService", function($http){
var serviceUrl = "http://some-web-page/service.asmx/";
var logOn = function(username, password){
var getUrl = serviceUrl + "logOn?username="+username+"&password="+password;
$http.get(getUrl).then(
function successCallback(response){
console.log("Success");
console.log(response);
}, function errorCallback(response){
console.log("Error");
console.log(response);
}
);
};
return {
logOn: logOn
};
}).config(function($httpProvider){
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
and in the console I am getting
HTML1300: Navigation occurred.
File: home
HTML1503: Unexpected start tag.
File: home, Line: 5, Column: 1
SEC7118: XMLHttpRequest for http://some-web-page/service.asmx/logOn?username=username&password=password required Cross Origin Resource Sharing (CORS).
File: home
SEC7115: :visited and :link styles can only differ by colour. Some styles were not applied to :visited.
File: home
SEC7120: Origin http://localhost not found in Access-Control-Allow-Origin header.
File: home
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.

You cannot make a query to the remote server from your client side (regardless of which framework you are using, underneath it is all built on top of XMLHttpRequest) unless they enable and implement CORS on their side (server hosted at http://some-web-page/service.asmx/ ). You can make the request to your server and from your server to the remote server instead, however this is not always an ideal solution.

For chrome and mozilla there is a plugin called cors install it, There will be no problem like cors.
https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Related

calling Https url on Http get request angularjs

I have a Https url and want to send request to get data from that URL , scenario 1:
from my browser If I hit the Url i get the response whereas from my Angularjs App I get always an error 401 , but if I hit the Api from browser I always get the correct response
for security reasons I couldn't use Url here but what I want is to:
$http({
method: "GET",
url: "https://urlAdresss/",
headers: {
"Accept-Language": "en-US, en;q=0.8",
"Content-Type": "application/json;charset=UTF-8"
},
}).then(function (_response) {
console.log(_response
}
I always get unauthorized I am network as well as On console any help will be greatly appreciated ,
but If I hit the same Url from browser I get the response It means the backend is working fine
I think I am missing something in my get request that's why getting the error
It seems a CORS (Cross-Origin Resource Sharing) issue.
In AngularJS side, you should use the following configuration in order for $http service to automatically send authorization headers to http requests.
var app = angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
});
And in backend you should specify explicitly allowed origins (eg. http://localhost:8888).
Also, note some points from here.
If you want to allow credentials then your Access-Control-Allow-Origin must not use *.

Angular $http.post not working, works using postman

I've created an Ionic app which calls an API to post the user's current location.
The request works as follows:
POST: http://mywebsite.com/api/Patients/AddLocation/17
with body:
{
"Latitude": 51.3753786,
"Longitude": -0.0833691
}
However, the following code in my Ionic app does work:
$http.post('http://mywebsite.com/api/Patients/AddLocation/' + $scope.id, data)
.success(function () {
console.log('Updated location');
})
.error(function (error) {
console.log('Error updating location');
console.log("Error: " + error);
});
In which 'data' is the same as the body above.
Any ideas why this isn't working?
UPDATE:
Here's a couple of screenshots of the network request:
Network request available at imgur RWNDF.png
Postman request
It happens if you have not enabled cors in your server.
enable cors in you server.
even if you dont enable cors,
get method will work peerfectly if you have enabled cors using any extension in chrome.
It's because of CORS. Enable cros from the server end and the a header will be set in HTTP Access-Control-Allow-Origin: * .
If your server app is an expressjs app, use below code to enable CORS
var cors = require('cors');
.....
app.use(cors());
Else use chrome extension Allow Cross Origin Request
This should solve the problem
After comparing this to a sister app which uses the same API and works, the only difference I could see was that a few of the plugins were different.
To remedy this I deleted the plugins folder and the platforms folder, re-added android and just the plugins I need, it now works. I guess it's maybe some bug I created by using the wrong mixture of plugins.
A very unsatisfying answer, but all requests work now!

AngularJs No 'Access-Control-Allow-Origin'

I'm trying to make a request with Angular like this:
(function () {
'use strict';
angular.module('app')
.service('requestService',requestService);
function requestService($http) {
this.post = function(url, data) {
return $http({
'method': 'POST',
'url': url,
'data': $.param(
data
)
});
}
}
})();
I receive the error in my console:
XMLHttpRequest cannot load http://lsupport.dev/api/v1/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
My http://localhost:3000 is build with Gulp. I've already searched a lot on the web, but I cannot find a solution.
You need to enable CORS on the server (remote) to permit the code to execute requests with a different domain.
CORS-Wikipedia
You must need access of the server in which your making the request OR owner of the server need to enable it.
Please check the following post in more details.
Header set Access-Control-Allow-Origin in .htaccess doesn't work
Access-Control-Allow-Origin Multiple Origin Domains?
Homestead is Nginx server Please follow the steps. To solve it.
Handling CORS with Nginx
Access Control Origin nothing to do with AngularJS, It server end issue to respond to the specific request there is different configuration based on your server type like Apache, Nginx.

how to download google drive file in angular

I have an angular app which uses a google drive picker to allow the user to select a file to download. In the google developer credentials area, I have the javascript origins and referrers set up to use localhost:3000 so the picker opens just fine. However, from that point, I can't seem to get the selected file. Here's the angular code where it tries to download the file.
$scope.$watchCollection('googleFiles', function (newGoogleFiles) {
if (newGoogleFiles.length > 0) {
$scope.filename = newGoogleFiles[newGoogleFiles.length - 1].name;
$scope.fileUrl = newGoogleFiles[newGoogleFiles.length - 1].url;
var deferred = $q.defer();
$http.get($scope.fileUrl, { responseType: 'arraybuffer'})
.success(function (data) {
console.log(data);
deferred.resolve(data);
});
return deferred.promise;
}
});
Instead of getting a file I get - XMLHttpRequest cannot load https://www.google.com/a/##############/edit?usp%3Ddrive_web&ltmpl=docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I'm guessing I need to set up something in the $http.get request for the file, but I have no idea what. Anyone have any idea? Thanks.
What you're dealing with is "CORS" (Cross-Origin Resource Sharing).
'Access-Control-Allow-Origin' header is something that has to be set on the server. You can probably log into google app settings and tell it what "origins" it can expect (ex: localhost, www.yourwebsite.com).

angular js empty error response

Trying to do some basic REST services from angular, but all I get back is an empty error response.
I open the index.html directly on my PC (not sure if this is the issue), and then click 'login' which eventually calls my controller:
$scope.doLogin = function()
{
var pr = $http.get('http://localHost:7777/BuilderDBSvc/login', {params: {user: $scope.userid, pass: $scope.password} })
.success(function(data)
{
console.log(data);
domains = data;
})
.error(function(data, status, headers, config)
{
console.log(data)
console.log(status)
console.log(headers)
console.log(config)
});
pr.then(function(data)
{
$scope.user = data.data;
});
};
Using firefox to debug, I put breakpoints inside all 3 functions: success error and then. But only 'error' is triggered. And the request always shows up in red, but with a 200 response code. The response data shows a size of 23 bytes, but the value is always blank.
However, if I type the URL and parameters directly in my browser window, it works fine, and displays the expected json string.
Ive used this pattern before, but with nodejs and angularjs working together. but this time the REST provider is a non-java application. I would suspect that is the problem, but when I enter the REST url directly in my browser it works fine.
What am I missing here?
Are there any better tools i can use to help debug this?
note:
yes this is a very insecure way to do authentication, but its my starting point.
Is highly probable that your ploblem is by opening the index.html from your explorer because the request will not come from localhost and by that the localhost server will block the request against cross origin request in chrome console youll probably see a message saying
XMLHttpRequest cannot load 'http://localhost:7777'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'your index.html location' is therefore not allowed access.
to avoid that you should make request from http://localhost to http://localhost (same server) or tell your server to accept cross origin requests

Resources