405 method not allowed using $http service AngularJS - angularjs

I'm getting a 405 error making a request from localhost, this is the full error:
OPTIONS http://www.myurl.com 405 (Method Not Allowed)
XMLHttpRequest cannot load http://www.myurl.com. Response for preflight has invalid HTTP status code 405
I understand the problem but the quirk is that I get this error just when I use the angular $http service:
var req = {
method: 'POST',
url: 'http://www.myurl.com',
headers: {
'Content-Type': 'application/json'
},
data: {
}
}
$http(req)
.then(function(res) {},
function(error) {});
Using XMLHttpRequest works perfectly:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("POST", 'http://www.myurl.com', true);
xhttp.send();
I have a chrome extension to add CORS headers and it is working. I also notice that if I remove the third parameter in xhttp.open the error appears again.
¿Does anyone know the reason? ¿How can I use the angular services without get the error?

You can write like this. Because you are not sending any parameter to the url. So I think this is a good way to do this. just try it may work for you.
$http.post('http://www.myurl.com').
success(function(data) {
//success Response here
});

You need to allow OPTIONS method on your server side. Before every GET, POST, PUT, DELETE... requests an OPTIONS request is launched.
I advise you to disable your "chrome extension to add CORS", to have the same configuration of your final users.

Related

Cross Origin Request when Access-Control-Allow-Origin missing

I am calling the url from server side language using nodejs. When i use that url on the client side, I am getting the CORS error. If I use POSTMAN then i am getting the reponse. I have searched through various forums and questions on Stack Overflow and I can't seem to find any solution to this. It would be appreciated if someone could provide some insight.
app.controller('Ctrl',['$scope','$http', function($scope,$http) {
var config = {
headers: {'Access-Control-Allow-Origin': 'https://developer.mozilla.org'}
}
$http({
url: 'http://localhost:8000/psp/getbank',
method: 'GET',
})
.then(
function successCallback(response) {
$scope.cspinfo = response.data;
console.log('Data Displayed successfully')
},
function errorCallback(response) {
console.log("Error:" + response.data)
})
}]);
The 'Access-Control-Allow-Origin' header is sent FROM the server, to let the client know where requests can come from. This is not a header you send TO the server.
This article specifies (among other things) the headers you are allowed to send in a CORS request: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Can't include header in `$http` angular

I got a token from backend which I saved it in $sessionStorage and I need to include that along with $http request that I call. I tried include it directly but when I checked it from backend, it's not there.
function _selectGender($sessionStorage, gender) {
return $http({
method: 'POST',
url: config.apiURL + '/auth/gender',
headers: {
'Authorization': $sessionStorage.token
},
data: {
gender: gender
}
}).then(updateCompleted).catch(updateFailed);
}
I also tried with interceptor which it's not working as well.
requestInterceptor.inject = ['$sessionStorage'];
function requestInterceptor($sessionStorage){
return {
'request': function(config){
if ($sessionStorage.token) config.headers['authorization'] = $sessionStorage.token;
return config;
}
}
}
Shoot me some idea how to tackle this. :D
Edit#1: It's likely possible to be preflight error
It's actually because of OPTIONS headers, seem like $http will send a pre-request before browser send an actual request to backend. You need to handle that from the backend. Thanks #Nitish Kumar's comment.
Read more about cors
How to handle OPTIONS

Request Forbidden 403 when request made to Square-Connect from localhost

I am trying to make a request to 'https://connect.squareup.com/v2/locations' using angularjs, where call is getting failed saying 403 FORBIDDEN.
Here is the code sample :
var url = 'https://connect.squareup.com/v2/locations';
var config = {
headers: {
'Authorization': 'Bearer sandbox-sq0atb-JJGltCa375qzAyoQbjPgmg',
'Accept': 'application/json',
"X-Testing": "testing"
}
};
$http.get(url, config)
.then(
function (response) {
console.dir(response);
},
function (response) {
console.log("failed" + response)
}
);
I have made a fiddle of the above sample. Any help is appreciated.
http://jsfiddle.net/dx6tdrha/
Are you seeing this error: XMLHttpRequest cannot load https://connect.squareup.com/v2/locations. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.? It means that you cannot access the API via front-end Javascript (like AngularJS) You'll need to use a different implementation like Node.js, PHP, etc.

Response for preflight has invalid HTTP status code 403 on angular post request

I am having an $http request in my localhost which is calling a url of some api. I am getting an error on executing the call
Response for preflight has invalid HTTP status code 403
Can I do anything using angular so that I can fix this issue? I have CROS plugin of chrome to allow cross origin request
$http({
method: 'POST',
url: url,
data:data1,
headers: {
'Access-Control-Allow-Origin': '*',
}
})
If you using java restful controller as your server.
You can refer to https://spring.io/guides/gs/rest-service-cors/
I added #CrossOrigin(origins = "*") on my controller and it works.
Basically, you cannot do anything in the client side.
Lin
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
AngularJS POST Fails: Response for preflight has invalid HTTP status code 404
I have this code in angularjs:
$http.post('http://localhost:8080/employee/'
, $scope.alumno
,{headers: {'Content-Type': 'application/json'}}
).success(function(data){
if ( data.err === false ) {
$scope.actualizado = true;
setTimeout(function() {
$scope.actualizado = false;
$scope.$apply();
}, 3500);
};
});
My API have this data:
//Add employee:
Url: http://localhost:8080/employee
Type request: POST
Add a new employee:
{
"firstName": "Javier",
"lastName": "Piedra",
}`
I use chrone with extension for available CORS for the GET all perfect but post sample this error:
XMLHttpRequest cannot load http://localhost:8080/employee/. Response for
preflight has invalid HTTP status code 403
In my app.config use:
app.config( function($routeProvider,$httpProvider){
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
Maybe this can be a solution for your issue.
Regards

AngularJS POST fails with No 'Access-Control-Allow-Origin' when using data payload object but works using query params like payload

I am facing a weird issue. I am running my angularjs app in nodejs server locally which calls a POST API from my app located on Google App Engine. The API is configured with all CORS headers required as follows:
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers.add_header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With, content-type, accept, myapp-domain")
self.response.headers["Content-Type"] = “application/json; charset=utf-8”
GET requests to the API work without issues.
POST requests to the API work but ONLY when I send the post data as a 'string of params' and NOT when post data is sent as an object which is the right way to do. Eventually I need to be able to upload pictures using this API so the first solution below might not work for me. Please help!
METHOD 1: This works:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = "conversationid=1c34b4f2&userid=67e80bf6&content='Hello champs! - Web App'";
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz",
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
METHOD 2: This fails:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = ({
'conversationid' : '1c34b4f2',
'userid' : '67e80bf6',
'content' : 'Hello champs! - Web App'
});
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz"
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
When I use METHOD 2 it fails with the following error in the console:
XMLHttpRequest cannot load https://myapp-qa.appspot.com/message.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://0.0.0.0:8000' is therefore not allowed access.
Please let me know if you have any solution. Thanks in advance.
The issue is most likely with Angular sending a pre-flight OPTIONS request to check the access headers from the server. I am not sure how OPTIONS requests are handled in your API, but I am betting these headers are not being added. I suggest installing Fiddler to monitor the actual requests to see what is going on with the headers. You may only be adding them to your POST responses.
See this answer for details on why METHOD 1 may work in this scenario, while METHOD 2 does not.
Here are some more details about pre-flight requests.

Resources