angular js empty error response - angularjs

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

Related

Here Maps Geocode API leads to Cross-Origin error

I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html
My JavaScript coding looks almost the same as in the official documentation:
var platform = new H.service.Platform({
'apikey': 'HERE IS MY API KEY'
});
// Get an instance of the geocoding service:
var service = platform.getSearchService();
service.geocode({
q: 'Berlin'
}, (result) => {
result.items.forEach((item) => {
console.log("test");
});
}, alert);
However, when the geocode request is sent, I get the following error:
Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.
Yes, the server will help with the issue. I'm here to suggest the alternative.
You can do the geocoding with the HERE Maps REST as well see docs — https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html.
Since not all the browsers historically support the CORS (learn more about the CORS — https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) there is an approach, called JSONP. See some JSONP explanation Here Maps related in the old docs https://developer.here.com/documentation/places/dev_guide/topics/request-cross-domain-js.html.
Eventually the https://www.npmjs.com/package/jsonp npm package could be a good follow up and we can get something like this after installing the package (npm install jsonp --save).
import jsonp from 'jsonp';
jsonp('https://geocode.search.hereapi.com/v1/geocode?q=5+Rue+Daunou%2C+75000+Paris%2C+France&apiKey=my-api-key',
null,
(err, data) => {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
This works great from my experience.
If you are testing this code by opening the file in the browser, you may get this error. I suggest using a local server for testing.

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 $http request to Web Service requires CORS

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

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).

Resources