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

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

Related

Cross domain issue in Google API's using angularJs

I am using following code to get the location details from the google API.
My code :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$scope.$apply(function(){
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true').then(function(res){
alert(res.data);
});
});
});
}
When I try this code I am getting the Cross domain Error.
My Error:
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?latlng=8.5663029,76.8916023&sensor=true. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Please suggest to solve this issue
You're sending an Authorization header ... which causes a CORS preflight check, and google doesn't like the Authorization header
you need to remove this header from the API call
see if this helps
$http.get("your long url", {headers: {Authorization: undefined}})
obviously I've replaced the actual url for readability
I've also seen the following suggestion
$http( {
method: 'GET',
url: 'someurl',
headers: {
'Authorization': undefined
}
}
)
so, rather than using the $http.get "shortcut", use $http "general" request format
I had the same issue; I was using the satellizer module for authentication.
https://github.com/sahat/satellizer
As it says on the FAQ section:
"How can I avoid sending Authorization header on all HTTP requests?"
I did:
$http({
method: 'GET',
url: 'your google api URL',
skipAuthorization: true // `Authorization: Bearer <token>` will not be sent on this request.
});
And it solved my problem; maybe you are using a third party module that modifies the header.
I can't answer in the threat of the response i want, but
Maybe your are using Interceptors in your AngularJS application, so your request is modified some time later after your configure the:
{headers: { Authorization: null } }
I'm doing more research to overcome this. I'll post my finds later.
[Edit] Wed Jul 13 2016 21:38:03 GMT-0500 (CDT) [/Edit]
My solution to this, is going with straight Javascript, in that way my petition does not is intercepted by Interceptors from the $http Service and does not have the Authorization header.
So, maybe this help someone.
Cheers!

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);
});

No 'Access-Control-Allow-Origin' header error yet the POST goes through anyway

So, I have this JavaScript function, that does a simple jQuery AJAX() request:
function impLeads() {
var go_health_id = $(".sync-action").data("subscriber");
var customer_number = $(".sync-action").data("customer-number");
var lead_type = $(".sync-action").data("lead-type");
var person = {
lead_type: lead_type,
customer_number: customer_number,
subscriber_id: go_health_id,
first_name: "Daniel",
last_name: "Endo",
phone: "(937) 555-5555"
}
$.ajax({
type: "POST",
crossDomain: true,
dataType: "json",
data: person,
url: "https://www.brokeroffice.com/leads/leadImport.do",
cache: false,
success: function(html) {
$(".debug").show().html(html);
console.log('Leads imported for ' + go_health_id);
}
});
}
Now... this is a HTTP post to BrokerOffice.com. Lead data can be imported to BrokerOffice via HTTP POST. The Endpoint URL = https://www.brokeroffice.com/leads/leadImport.do. I am executing this script from http://mycompanysite.com/leads/. Notice that they have https:// and www while mine do not.
However, when I go into BrokerOffice.com, I see that the lead was successfully posted into their database so... despite this warning:
XMLHttpRequest cannot load https://www.brokeroffice.com/leads/leadImport.do. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mycompanysite.com' is therefore not allowed access.
The request went through.
The problem is that I have to this request on loop more than once so that JavaScript error will stop the loop from continuing the execution.
What can I do?
That header just stops you from being able to see a response from the server (not from sending a request).
The problem is that I have to this request on loop more than once so
that JavaScript error will stop the loop from continuing the
execution.
What can I do?
What can you do? The response header from the server needs to be changed to allow cross-origin communication. If you don't have access to changing the server, then you might be out of luck.
As #apsillers mentioned, you can send requests and they'll get there. You just can't get responses.
If you need to read the response, you can:
Use a light CORS proxy like https://github.com/gr2m/CORS-Proxy on your server.
Use a hosted proxy like http://crossorigin.me/

CORS blocks LinkedIn share API

I try to post new content using LinkedIn share API through JavaScript from AngularJS application as given below.
var xml = "<share><comment>" + content + "</comment><visibility><code>anyone</code></visibility></share>";
var req = {
method: 'POST',
url: 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=' + account.token,
headers: {
'Content-Type': 'text/plain'
},
data: xml
};
$http(req).success(function(data) {
console.log(data);
console.log('published to linkedin');
}).error(function() {
console.log(arguments);
console.log('failed to publish to linkedin');
});
I can successfully POST this data. However the browser blocks the response from being read because the response doesn't have an 'Access-Control-Allow-Origin' header.
But, I have given the http://localhost:3000 and 'https://localhost:3000' domains in LinkedIn application settings.
And the request/response in Chrome looks like this.
Any thoughts on how to be able to read the response and not let the browser block it?
I think the problem is the missing Access-Control-Allow-Origin header in the LinkedIn API response?
Looks like LinkedIn's REST API doesn't support CORS. They suggest to use REST API from the backend and not from browser. JS-SDK must be used from the browser.
https://developer-programs.linkedin.com/forum/cors

Reddit API /api/morechildren returns "No 'Access-Control-Allow-Origin' header" using mootools

I've tried the following basic Reddit API morechildren request using mootools:
var moreChildren = new Request({
async: true,
url: 'http://www.reddit.com/api/morechildren',
method: 'post',
data: {
api_type: "json",
children: "cl2vjlp",
link_id: "2ijczu",
sort: "top"
},
onSuccess: function(response){
commentData = JSON.parse(response);
console.log(commentData);
}
});
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
moreChildren.send();
And I'm receiving a XMLHttpRequest cannot load http://www.reddit.com/api/morechildren.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403. in Google Chrome.
Observations:
Adding .json to reddit/api/morechildren(.json) does not resolve
deleting "X-Requested-With" header does not resolve
Any help is greatly appreciated. :)
This is because of same origin policy - CORS.
you do well to remove this:
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
but if the reddit site does not support it, it won't work.
you have 2 options:
local proxy, ajax call to local, local server-side to reddit, back and output to browser
use JSONP where available.
can't test your case as it needs oauth but via info.json which is GET, you can:
http://jsfiddle.net/dimitar/zy3rwpjs/
new Request.JSONP({
url: 'http://www.reddit.com/api/info.json',
callbackKey: 'jsonp',
data: {
url: 'http://www.reddit.com/buttons'
},
onSuccess: function(response){
console.log(response.data, response.kind);
}
}).send();
obviously, when it expects POST, things get more complex... JSONP works as GET.
if all you care about is your own project and google chrome, you can start with with --disable-web-security flag, which will allow the call.

Categories

Resources