angular.js $http.post not working in phone - javascript

I have a big problém,
I made a small application ionic , angularjs that works without error,
when I add $http.get() call to receive a JSON file
the browser displays the error:
XMLHttpRequest cannot load ..... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
$http.get("http://elite-schedule.net/api/leaguedata")
.success(function(data) {
deferred.resolve(data);
}) .error(function() {
console.log("Error while making HTTP call.");
deferred.reject();
});
I add the extension Allow-Control-Allow-Origin: *
and the application returns run
but my problem in my phone (android) it does not display anything
I think we should allow this appeal $http.get
please, who knows display console.log () in the phone , to know the source of the error or who has already this error
thank you a lot

This kind of question occurs every day. Firstly read about CORS: https://ru.wikipedia.org/wiki/Cross-origin_resource_sharing
Then if you can change server configuration, then do it(if it's ok for your security policy, of course). If not, do jsonp request. If it's not available either.. find another API.

Related

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

Access Control Allow Origin Issue with AngularJS

I have seen several related issues about this on here but none has solved my problem yet.
I am trying to access the freckle(letsfreckle.com) api in a small web app I'm building but I'm having issues. It works when I start chrome browser without security but its not working on github pages and when I package the app as a chrome extension.
This is what my service looks like
jXtnsion.factory('freckle', ['$http', function($http){
return $http.get('https://api.letsfreckle.com/v2/projects?freckle_token=kacgnpf0og0hfi1it32o9xtc2ls2328-gmeb1nwcp1ko8o0f0ygi4mlxxxxxxxx&f&format=jsonp')
.success(function(freckleData){
return freckleData;
})
.error(function(err){
return err;
});
}]);
I keep getting a 'XMLHttpRequest cannot load https://api.letsfreckle.com/v2/projects?freckle_token=kacgnpf0og0hfi1it32o9xtc2ls2328-gmeb1nwcp1ko8o0f0ygi4mlxxxxxxxx&f&format=jsonp. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://andela-asogbein.github.io' is therefore not allowed access.
Why is this not working?
I think your server needs to correctly respond to the OPTIONS request that the browser will make on your behalf to determine if the CORS request is valid. It needs to contain an Access-Control-Allow-Headers header with the right info in it.
You can refer to this:
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests
I resolved this by including
"permissions": [
"https://*/"
],
in my manifest.json file so it works without problem as a chrome extension. the problem seems to be from the freckle api as for the issue with local host

No 'access-control-allow-origin' header is present in AJAX request

I am using the following URL to get data for a weather app.
http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP
I've used this API before, but this time I'm trying to load the data in using AJAX so the rest of my page doesnt reload when this data is fetched.
Here is my javascript
<script>
$(function () {
var zip = 16001;
$.ajax({
type: 'GET',
crossDomain:'true',
url: 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP' +zip,
success: function (data) {
console.log("Here is the data", data);
},
error: function () {
alert("Error loading data");
}
});
});
</script>
I keep recieving the following error in the console.
XMLHttpRequest cannot load http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP16001. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50733' is therefore not allowed access. The response had HTTP status code 500. weatherAjax.html:1
This makes it seem like their is an issue with accessing the data. But i've used this before with a simple form that the user input their zip code into. And it returned the data. The only difference now is I want to load the data using AJAX so the entire page doesn't reload. What am I doing wrong?
Previously you were sending the user's browser to someone else's website. They were leaving your site and all was fine.
Now you are trying to write JavaScript to instruct your visitor's browser to fetch data from someone else's website (which would use any auth/authz credentials they had) and give that data to your code.
Since the other website could be, for example, an online bank, this is forbidden unless the site you are requesting the data from gives explicit permission for you to access it.
For further reading, see the Same Origin Policy and HTTP access control (CORS).

Access an API from local server

I am trying to call the CTA API (http://www.transitchicago.com/developers/bustracker.aspx) from my local Wamp server. However, when doing the fetch via backbone collection I get:
XMLHttpRequest cannot load http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
collection:
define([
'models/route',
'core'
], function (Route) {
return Backbone.Collection.extend({
initialize: function () {},
model: Route,
//url: function () {
// return 'http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx';
//},
url: function () {
return '/apiproxy.php?method=getroutes';
},
});
});
I know this is a common issue but haven't found a concise answer yet.
How can I resolve this issue?
Update
Added the apiproxy but am getting this response:
Remote Address:127.0.0.1:80
Request URL:http://localhost/apiproxy.php?method=getroutes
Request Method:GET
Status Code:200 OK
Request Headersview parsed
GET /apiproxy.php?method=getroutes HTTP/1.1
console:
responseText: "$url = "http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}? key=xx";
↵echo file_get_contents($url);
SyntaxError {stack: (...), message: "Unexpected token $"}
message: "Unexpected token $"
stack: (...)
You can solve this problem, but it's not a simple case of "add this line to your JavaScript and everything will be fine."
You're running up against the same-origin security policy built into every web browser. 'Origin' basically means 'the same site'; my JavaScript on example.com can access whatever it likes on example.com, but it's not allowed to read anything from demonstration.com, example.net, or api.example.com. That's got a different origin. Here's a table of what counts as the same origin.
Without it, I could write a web page that steals all your gmail and private Facebook photos. My malicious JavaScript would make web requests to gmail.com and facebook.com, find the links to your emails & photos, load that data too, and then send it off to my own server.
Obviously, some web pages are designed to be used by other people. APIs, for instance, generally want to allow access to their data so people can build web apps. The people building those APIs can serve their content with Access-Control- headers that tell browsers it's OK to allow requests from other sites. This is called CORS - Cross-Origin Resource Sharing. The reason you get that error message is because the ctabustracker.com developers haven't added any CORS headers. Thus, you can't access their API from your JavaScript.
So what's the solution? you have two options:
Email the ctabustracker.com admins and ask them to add CORS headers to allow access from other domains. This is the least work for you, but you're at the mercy of the knowledge, infrastructure, & promptness of their development team.
Write your own proxy server.
The same-origin policy is only standing in your way in your JavaScript. You can do whatever you like on the server; at its simplest, you could create an apiproxy.php along these lines:
$allExceptMethod = $_GET; // PHP arrays are copy-by-value
unset($allExceptMethod['method']);
$url = "http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?key=xx&" . http_build_query($allExceptMethod);
echo file_get_contents($url);
And then access it from your JavaScript as /apiproxy.php?method=getroutes, and pass extra parameters in via a standard query string (for instance, /apiproxy.php?method=test&foo=bar&cat=dog results in a request to http://www.ctabustracker.com/bustime/api/v1/test?key=xx&foo=bar&cat=dog). Now your JavaScript is making a request to your own server, so you won't have any problems with the same-origin policy.
You can, of course, make your proxy as smart as you like. It could cache responses, convert your XML to JSON, pre-fetch the results for likely next requests, or 100 other things that may be useful for your app.

Categories