Access-Control-Allow-Origin issue and angular $http service - javascript

Sorry for duplicating a question for this issue but I really tried to seek for a solution but I could not find it. So I use angular $http.get xhr request to retrieve data from the public api. I have next code
$http.get('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" );
});
this returns in console:
XMLHttpRequest cannot load http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'blah-my-localhost-blah' is therefore not allowed access.
However if I user jquery getJson method it works just fine:
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", {cmd:"getMakes", year:"2009"},
function(data) {
console.log(data);
});
So obviously I can configure angular to send correct request since jQuery works fine?
Thank you for the response.

Use the $http.jsonp method to do a jsonp request along with JSON_CALLBACK as the callback name:
$http.jsonp('http://www.carqueryapi.com/api/0.3/?callback=JSON_CALLBACK&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" ); });

Related

Having issues getting page title from html with meteor.http package

Meteor.http.call( 'GET', 'http://google.com', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
the problem is it keeps showing this error this is my first time using this package so am not sure if i really understand it.
this is the error on my console.
XMLHttpRequest cannot load http://google.com. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
HTTP Requests from the browser will always run into this CORS issue unless you specifically allow them with CORS headers.
Meteor has a good way of dealing with it. First up you do a call:
Meteor.call("httpRequest","http://myserver.com/path/to/file",params);
In the server you write a Meteor method like this
Meteor.methods({
httpRequest: function(url,params) {
// Send the http request here
})
});
You cannot do a call back to the client with the result of the http request, but you can put it into a database record, which the client subscribes to.

Error access-control-allow-origin on angularjs $http.post

I wrote simple code with angularjs to communicate to PHP server API that I hosted in shared server before. I used $http.get and $http.post to get data from the server but it returned error 'access-control-allow-origin' like below:
http://dpmp.arkoding.tk/index.php/api/datapost. 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:8100' is therefore not allowed access.
The response had HTTP status code 404.
access-control-allow-origin
most of the references that I got explained that it caused by CORS enabled on server site and just simply add a line 'header('Access-Control-Allow-Origin: *');' at the top for fix it. I have done that but it just fixed '$http.get' function and I still got the same error for '$http.post'. And made me more confused because it worked if I used postman and I thought the problem was in my angular code.
I have tried add some code in my services.js shown on the snippets below:
var datac = {id: 'helo'};
var head = {'Content-Type': 'application/json'};
return $http({
url: url + '/datapost',
method: 'POST',
headers: head,
data: datac
});
and without header
var datac = {id: 'helo'};
return $http({
url: url + '/datapost',
method: 'POST',
data: datac
});
but it wouldn't work. I even have tried to move my rest API to another hosting provider and it also returned the same error when I used angular $http.post.
I'm very appreciated for your help to my problem,
and I am sorry for my untidy english by the way :).
SOLVED IT! finally... :D
based on this link, finally I fixed the problem..
Thanks...

How to get JSON with jQuery from another domain

I have a little page and I need to get JSON from another domain. If make this:
$.get( "http://dev.frevend.com/json/users.json", function( data ) {
console.log(data);
alert( "Load was performed." );
});
I get an error. I understand why it throws this error, but I don`t know how to aviod it. I have not acces to the server.
XMLHttpRequest cannot load http://dev.frevend.com/json/users.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
I also tried to use JSONP, but as I understand in that case server should wrap response with callback function, because I got a SyntaxError.
Is it possible to make this request with JSONP?
I tried
$.ajax({
url: "http://dev.frevend.com/json/users.json",
dataType: "jsonp",
jsonpCallback: "logResults"
});
function logResults(data) {
console.log(data);
}
But got
Uncaught SyntaxError: Unexpected token :
JSON is valid, I checked.
You need to allow access in your project configuration.
Below site has more information
http://enable-cors.org/server.html
Thanks,
Use JSONP in jquery for this purpose JSONP reference
Try to add a header into your PHP file which is responsible for executing every request.
header('Access-Control-Allow-Origin', '*');

AngularJS $http.post() firing get request instead of post

i building an API service in angular and laravel, when i firing a GET call to the API everythings work fine, but when i fire POST call the service still use GET method instead of POST.
that is my service:
function LeadsAPI($http,$q,BASE_URL)
{
this.updateLead = function (lead_data) {
var url = BASE_URL+"/leads/update/";
var deferred = $q.defer();
$http.post(url , lead_data).then(function(response){
deferred.resolve(response.data);
});
return deferred.promise;
}
}
i call to this function from a Controller:
LeadsController.$inject = ['$scope', 'LeadsAPI'];
function LeadsController($scope , LeadsAPI)
{
LeadsAPI.updateLead({'lead_id' : res._id, 'the_lead': {'fist_name' : 'asd asd'}}).then(function (res) {
console.log(res);
});
}
i tried pass the parameters as a string ("a=b&c=d...") and added header :
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
in the run function at my App module instantiation but yet, i keep getting 405 (Method Not Allowed) error.
any ideas why and how to solve it? thank you very much all! :)
Seems the question is old and unanswered but google led me here. I hope someone will find this answer useful.
I had the same problem. $http was set to POST but server was returning error from GET request.
After checking the headers in a web inspector it shows the browser actually did two requests:
update/ 301 text/html angular.js:11442
update 405 xhr https://test.site/post/update
The first one is the one from $http and the second one is after a redirect.
As you can see the trailing slash URL is redirected to a non trailing one. With this redirect a POST request gets also changed to GET as well.
The solution is to change your request url to not contain trailing slashes:
url: BASE_URL+"/leads/update",
The GET works fine ... good
The POST returns 405 - Method not allowed
It sounds like it is doing a POST and the server you are posting to does not support POST requests to the endpoint in question
Can you please provide more information, such as the HTTP request and response headers when you make a GET request and the same for the POST request
You can access the header information via the NET tab in Firefox's Firebug or in Chrome console
Be sure that your API method is ready to handle a POST request. Maybe Angular is actually firing a POST request, but your method is expecting a GET.
If you are sure Angular is really firing a GET request instead of a POST for some reason, try to explicitly set the HTTP method on the $http object:
$http({
method: 'POST',
url: BASE_URL+"/leads/update/",
data: lead_data
}).then(function (response) {
deferred.resolve(response.data);
});

getjson - not returning object to console

I am trying to retrieve a json feed every 1 second. The URL that I am trying to retrieve displays JSON in the browser but will not be retrieved via a jquery getJSON
http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints
function getBusLoc() {
$.getJSON('http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints?callback=?', function(data) {
console.log(data);
setTimeout(getBusLoc, 1000);
})
}
getBusLoc()
It has something to do with the above link. What am I missing? Fiddle here
This is because of same origin policy, you can't sent ajax request from host A to host B, you can use jsonp instead (if your service supports this) , or if you has control to server side and you don't mind to old browsers you can use x-access-control-allow-origin http header in response to OPTIONS request (more info here https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)

Categories

Resources