angularjs1.4 CORS failed - javascript

I'm using AngularJS 1.4.3. Here's my code:
angular
.module('app', [])
.run(run);
function run($http) {
a = $http({
method: "GET",
url: 'http://127.0.0.1:8080/test',
data: {}
});
console.log(a);
}
Using browser or Postman can get it correct. But the code above gives
XMLHttpRequest cannot load http://127.0.0.1:8080/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
The point is, I can use GET method to get the result using applications. But using code won't work. What have I done wrong?

The point is, I can use GET method to get the result using applications.
In that instance, there is the application and the server and nobody else. There are only two entities involved.
But using code won't work.
You have two different websites (localhost:8000 and localhost:8080) and the browser doesn't know if the JavaScript provided by 8000 can be trusted with the data that 8080 is willing to give to the user.
What have I done wrong?
You haven't provided an Access-Control-Allow-Origin header in the HTTP response from 8080 to tell the browser that 8000 can be trusted with the data.
See also:
The specification
The MDN documentation

Related

GetAddress.io and 'No Access Control Allow Origin' error

I'm trying to use getAddress.io, and while the syntax is very simple, I'm trying to write my backend management that can get whitelisted domains and usage etc.
So here is my call in jQuery:
$.ajax({
url: " https://api.getAddress.io/v2/usage",
context: document.body,
method: "GET",
data: {"api-key": getAddressAPIKey}
}).done(function(results) {
$("div.usage").append(results);
});
All seems to be up to scatch. However it returns the following error:
Failed to load https://api.getaddress.io/security/ip-address-whitelist?api-key=[apikey]: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.awme.local' is therefore not allowed access.
What am I doing wrong? I understand what the error is about as I've written my own APIs but this is a public API that I obviously dont have control over - and so therefore I cannot modify their code to allow me access. This is a paid for service so I should just be able to query it and get my data back. Why am I getting this error?
You need to whitelist either your domain(if you are accessing the API from client), or your server IP if using backend.
https://getaddress.io/Documentation#domain-whitelist
Just make a simple post request with you admin-key(NOT API KEY) the params(NOT IN BODY) and your domain name in the body and set Content-Type to application/json.
Here is an example request with the response using postman.
The problem is that the API has CORS set up. Try adding dataType: "jsonp" as a parameter in your AJAX request. If that doesn't work, try using something like https://cors-anywhere.herokuapp.com/
You cannot query directly from the browser, you have to query through a proxy like nginx or apache. You throw your request to the proxy and the proxy passes them to the other public API
May be the return type from the controller was not provided , This error mostly occurs when
return type is not mentioned or kept as dynamic and if the return type object contains any child elements .Just mention a proper return type.
The URL in your error message:
'https://api.getaddress.io/security/ip-address-whitelist?api-key=[apikey]'
..is not related to the code you have provided.
I assume there is more code in in your page that uses the above URL?
Did you read its document? I'm not familiar with this getAddress.io, but it seems you have to add your domain and IP to its whitelist.
Checkout Domain Whitelist and IP Address Whitelist

How to handle CORS in a service account call to Google oAuth?

I access a Google calendar using a service account. This means that the owner of the calendar will not be prompted for his authorization.
This works fine in Python, where I make a requests call to https://accounts.google.com/o/oauth2/token with a specific body. This gets me back a token I can use later.
I now need to have an application running in a standalone browser (Chrome - without user interaction) and tried to directly port this call as
fetch('https://accounts.google.com/o/oauth2/token',
{
method: 'POST',
body: JSON.stringify(body),
})
.then(function(res) { return res.json(); })
.then(function(data) { alert(JSON.stringify(data)) })
but I get a reply from Google
Failed to load https://accounts.google.com/o/oauth2/token: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://devd.io' is therefore not allowed access. The
response had HTTP status code 400. If an opaque response serves your
needs, set the request's mode to 'no-cors' to fetch the resource with
CORS disabled.
My limited understanding of CORS (a previous answer was a very good read) is that
No 'Access-Control-Allow-Origin' header is present on the requested
resource
means that it is not present in the response headers, which means that Google does not want me to access its resources via JS when ran from the browser (which points to something else that https://accounts.google.com).
This may be a good idea but I control all elements, from the code to the browser and would like to get that token the same way I get it in a non-browser environment, specifically my working Python code.
How can I tell https://accounts.google.com to send me back a Access-Control-Allow-Origin header which tell my browser that it is OK to accept the call?
You can't.
Client side and server side code need to interact with OAuth in different ways.
Google provide documentation explaining the client side process.
Importantly, part of it involves redirecting to Google's servers instead of accessing them with fetch or XMLHttpRequest.
#Quentin's answer "You can't" is the right one for my question ("how can I force the server to send back the right header").
This is a decision at Google not to provide this header, effectively cutting off any non-interactive applications.
As a solution, I will look at
how to force the browser not to take into account the security mechanisms provided by CORS (there seems to be some ways through extensions or command-line arguments, I will update this answer once I find it)
or write an intermediate layer which will query the data for me and pass them verbatim to the application (this is equivalent, in my case, of just making the query from JS - but it adds an extra layer of code and server)

Reading json content from a REST API URL

I have built a REST API with Node.js Express http://localhost:3000/api/feeds with node.js and filled with data.
router.get('/api/feeds', function (req, res, next) {
documentDBConfig.getAllDocuments()
.then(() => res.json(documentDBConfig.feedsArray));
});
Now i make a static website and want to use javascript or jquery to get data from my REST API. I used this code
$.getJSON( "http://localhost:3000/api/feeds", function( data ) {
console.log(data);
});
But it keeps saying
XMLHttpRequest cannot load http://localhost:3000/api/feeds. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I know i'm doing it wrong, but i couldn't find the correct way. How can i get this json content with my website from my REST API (http://localhost:3000/api/feeds) ?
Edit: I don't get this warning with explorer, but i can not get the content. And now i solved the chrome problem thus i don't get this warning anymore. But i can't read the content. That is not a duplication.
Now i get this warning
Failed to load resource: the server responded with a status of 404 (Not Found)
Can you show us your REST api code so we can help you ? You need to set some headers in your backend to allow requests coming from other origins.
If you happen to be using express, this will help you. But you could have built the REST api in another way, so please provide us with more information.
This is because you are accessing a resource from another domain.
You try to access http://localhost:3000 from http://localhost:63342.
You can read more about this here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin
Basically you are performing a CORS request which means you are trying to call a resource on different server. So your REST api should allow CORS requests by adding the response headers allowing the UI server resource.
Please Refer to this question if it helps

No 'Access-Control-Allow-Origin' header is not present always shows no matter what url I try to use

I am trying to learn how to parse APIs using javascript and so I am trying to get some json through some get calls.
In my script I have
<script>
function foo() {
var request = window.superagent;
var url = 'http://www.google.ca';
request
.get(url, function(response) {
console.log(response);
})
.set('Accept', 'application/json');
}
foo();
</script>
No matter what url I use, I always get this error
XMLHttpRequest cannot load http://www.google.ca/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://server.com' is therefore not allowed access.
(index):22 Error: Origin is not allowed by Access-Control-Allow-Origin
at s.crossDomainError (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:7899)
at XMLHttpRequest.s.end.D.onreadystatechange (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:8551)
I tried using various example get request urls like wikipedia, nba stats, google etc...that work fine when I enter the url into my browser but it does not work when I try to use javascript to download the data.
I am using a local apache2 server on my ubuntu laptop. I am also using the superagent library for javascript, but i also tried using jquery and ajax and it's the same error.
so apparently I need to use a url that uses cors. The thing is
http://savvastjortjoglou.com/nba-shot-sharts.html?utm_source=Python+Weekly+Newsletter&utm_campaign=5185ff0538-Python_Weekly_Issue_202_July_30_2015&utm_medium=email&utm_term=0_9e26887fc5-5185ff0538-312727397
this tutorial just did a requests.get(url) which was the nba stats url and got his data. He did not get an error? How can I use a url that doesn't use cors to get data?
CORS is implemented on the browser end as well, to not allow javascript load malicious content from unknown sites. You should also try using the CORS plugin if you are still trying to scrap on the client side.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Bloomapi, XMLHttpRequest cannot load

I am currently using the API at www.bloomapi.com with AngularJS and keep getting this reject:
XMLHttpRequest cannot load
http://www.bloomapi.com/api/search?limit=1&offset=0&key1=npi&op1=eq&value1=1861733537.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
I'm not sure if the issue is BloomAPI specific (e.g. if I need an API key or something), or if there is something wrong with my API call.
This is my code...
FACTORY:
.factory('ProviderService', ['$resource', function($resource) {
return $resource('http://www.bloomapi.com/api/search?limit=1&offset=0&key1=npi&op1=eq&value1=:npi',
{npi:'#npi'}
)}
])
CONTROLLER:
ProviderService.get({npi:'1861733537'}, function(res) {
$scope.providerNPI = res.id;
$scope.providerName = res.result.last_name;
console.log($scope.providerName);
});
Thank you very much!
Based on the error, it looks like AngularJS uses CORS by default for $resource requests. BloomAPI doesn't currently support CORS but does support JSONP.
I haven't ever done JSONP in AngularJS before but found a few promising looking resources such as http://www.bennadel.com/blog/2610-using-jsonp-with-resource-in-angularjs.htm that may help resolve the issue.
Let me know if this doesn't work with your scenario for some reason, and I'd be happy to take a look at implementing CORS in BloomAPI sooner rather than later.

Categories