How to make cross origin get request via angularjs http using food2fork api - javascript

I'm simply trying to make a get request using food2fork's search api in an angular app. Right now I've got no backend to the app, so everything is running client side, and I'm running the following (with the APIKEY replaced, of course):
$http.jsonp('http://food2fork.com/api/search?q=turkey&key=APIKEY&callback=jsonp_callback')
.then(function(response) {
console.log(response);
});
However, I'm Uncaught SyntaxError: Unexpected token : in the console. I assume this is because it's expecting a jsonp function rather than json.
If I run it as a jquery getJSON, as seen here:
$(document).ready(function() {
var url = "http://food2fork.com/api/search?q=turkey&key=APIKEY";
$.getJSON(url,function(data) {
})
});
I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. - which may be because I'm running locally, but that hasn't been a problem in the past.
I just want to get the json that I get if I run the same request as a url in a browser. Any ideas?

No 'Access-Control-Allow-Origin' header is present on the requested resource
You are facing Cross Domain problem and what you should do is enabling CORS from your server side (the service running from localhost:8080)

Related

Accessing an external image via HTTP GET in javascript/angular

I can succesfully use a HTTP GET to retrieve an image via services like Postman and Hurl.it.
I'm now trying to obtain the same image via Angular HttpClient as blob. Code is basically as is:
this.http.get('via.placeholder.com/200x200',{ responseType: 'blob'}).subscribe(data => this.d = data);
Whether I use map and subscribe, I can't retrieve the image data. I always get the same CORS error in Chrome:
Failed to load via.placeholder.com/200x200: 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:4200' is therefore not allowed access. The response had HTTP status code 405
Now I know the "why is this working with Postman but not in my code" has been answered here.
That said, is there still a way, using javascript/angular and without using a proxy, to simply get an image from a website via HTTP GET?

Angular CORS with Amazon Product API

Created a MEAN stack app and I have an angular component that on page load is making a request to the Amazon Product API. I am running and testing locally on localhost (node/express backend).
Here is the basic request code in my component:
getAmazonTackle(amz:amazonservice) {
var req:Object = {
method: this.amazonservice.Method,
url: this.amazonservice.Endpoint,
headers: {
//"Access-Control-Allow-Origin":"*"
},
data: this.amazonservice.Data,
withCredentials: false
}
console.log(JSON.parse(JSON.stringify(req)));
this.$http(req).then(
function(response) {
console.dir('The response: '+response);
},
function(response) {
console.dir(response);
console.dir('The error:'+response);
}
)
}
When I don't have the Access-Control-Allow-Origin header, accessing the page in browser I'm presented with the following in the Chrome dev console:
XMLHttpRequest cannot load http://webservices.amazon.com/onca/xml?.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
When I add the Access-Control-Allow-Origin header, I receive the following:
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.
What I'm trying to determine is if I'm doing this incorrectly or if the amazon API doesn't support CORS.
I faced the similar issue and found that if I create cors enabled http handler that will work as middleware between your server and amazon server. This way we can solve this cors issue.
It is quite simple to create and I already written it.
Develop Angular2 Application with real server APIs
Check out the question and the answer in the above post.
Similar code I posted on github, if need I will share the location.
Note: As of now I handled the get request but adding other methods is fairly easy.
https://github.com/Anil8753/CORSHttpHandler

'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)

I'm getting an a "XMLHttpRequest cannot load https://example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access."
This is my componenDidMount(), and I'm using axios to get the data from my API.
componentDidMount() {
this.serverRequest = axios.get(this.props.source).then(event =>{
this.setState({
title: event.data[0].name
});
});
}
I'm using "python -m SimpleHTTPServer" on the terminal, to run 'http://localhost:8000'.
I'm using the Chrome browser, and if I turn on the Chrome CORS plugin (to enable cross origin resource sharing), the app works, and I see data displayed from the API on the DOM. But I know that using the CORS plugin is bad, so how should I fix the 'Access-Control-Allow-Origin' error officially?
With Axios, can I somehow add dataType: "jsonp", if that would fix it?
This is a restriction made by the browser for security reasons when you try to access content in some domain from another domain. You overcome this, you need to set the following in your header
Access-Control-Request-Method
Access-Control-Request-Headers
Many sites restrict CORS. The best way to achieve your goal is to make your python server as a proxy. See the example.
//Request from the client/browser
http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com
//In your server
1. Handle the request
2. Get the query param(url of the website)
3. Fetch it using your python server
4. Return the fetching data to the client.
This should work.

No 'Access-Control-Allow-Origin' header is present on the requested resource despite it is there

I have java application exposing its api as rest services. It is accessible on the following URL: http://localhost:8080
On the other hand I have Angular standalone client trying to call those services. This client is operating on different URL: http://localhost:8383
To avoid CORS issue I have added this to the response header of my rest services:
return Response.ok(result,
MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin",
"http://localhost:8080").build();
Now it appears no matter what I put as a value of this header:
http://localhost:8080
http://localhost:8383
(* - star)
client doesn't work complaining for the lack of this header:
XMLHttpRequest cannot load http://localhost:8080/PokerGame-REST. No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8383' is therefore not allowed
access. (16:24:11:684 | error, javascript) at app/index.html
What is the problem here, did I miss something?
It's worth mentioning that Advanced REST client returns the response as expected and the response headers contain this one: Access-Control-Allow-Origin. So it looks like purly my Angular app issue but why?
Another interesting thing is client behavior. When I use:
$http.get('http://localhost:8080/PokerGame-REST/').success(function
(response) { ... }
it fails with the error in question but when I use this:
var restCall = $resource('http://localhost:8080/PokerGame-REST/', {});
restCall.get(function (restResponse) { $scope.intro = restResponse; });
it fails with different error:
Response for preflight is invalid (redirect)
which is not true as the response is purly in JSON format.
Any ideas?
PJDef was right (second comment) and his suggestion helped me to resolve the issue.

getting json from external source in javascript

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

Categories

Resources