angularJS sending OPTIONS instead of POST - javascript

Im stuck at this 2 days I can not find a solution.
When im doing an AngularJS POST it Sends OPTIONS in the header and returns error from the API the code looks like this nothing special.
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post(URL, JSON.stringify(data)).
success(function(data, status, headers, config) {
alert(data);
error(function(data, status, headers, config) {
console.log("Error");
});
CORS is enabled on the API it has the Headers, when i do POST with fiddler or POSTMan in Chrome it works fine only when i use angularJS post it won't go thru.
why do i get OPTIONS /SubmitTicket HTTP/1.1 instead of POST?
What do i need to do to POST ? I have read about it it says something like CORS is adding OPTIONS header but why?

When you invoke the CORS requests, the browser always sends the OPTIONS request to server to know what methods are actually allowed. So this is the desired behaviour. This is so called: "Preflighted request", see: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ (section: "Preflighted requests")
Therefore in your case, you have to allow the OPTIONS method in 'Access-Control-Allow-Methods' header of your CORS filter.

My understanding is that angular initially sends an OPTIONS request to the server in order to ask the server if the full request is permissable.
The server will then respond with Headers specifying what is and is not allowed.
I guess this might be an issue with the server returning the wrong CORS headers.
You said that the server returns an error please post that error here.
See Preflighted CORS request at: http://www.staticapps.org/articles/cross-domain-requests-with-cors
and
AngularJS performs an OPTIONS HTTP request for a cross-origin resource

// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Should only need to do this code to get it to work:
angular.module('TestApp', [])
.factory('someService', ['$http', someService]);
function someService() {
var service = {
save: save
};
var serviceUrl = '/some/Url';
return service;
function save(data) {
$http.post(serviceUrl, data)
.success(function(data, status, headers, config) {
alert(data);
})
.error(function(data, status, headers, config) {
console.log("Error");
});
}
}
Then pull your someService into your controller and use:
someService.save(data);

Related

Handle a 404 when networks shows a 200

What is wrong with this code:
function mainCtrl($scope, $http) {
function loadData(){ $http.jsonp('http://www.pais.co.il/Lotto/Pages/last_Results.aspx?download=1')
.then(function (data, status, headers, config) {
console.log(data);
},
function (data, status, headers, config) {
console.log(data);
});
}
loadData();
};
I have a simple call to a URL.
I can see in my network that it was a success (200).
But my the response is beeing catch in the error function:
You aren't getting a 404 error. You are getting an invalid JS error.
You are making a JSONP request. The URL is returning CSV data, not JSONP.
You need to either:
Use a URL that returns JSONP
Use XMLHttpRequest instead of <script> (which is what $http.jsonp does behind the scenes) to load the data and ensure that the suitable Access-Control headers are set to give your JS permission to read the data
Fetch the data from your server instead

CouchDB XMLHttpRequest Error

I am using Angular to connect to a server running CouchDB that I have set-up. When ever I run the code I get the error:
"XMLHttpRequest cannot load http://ip:5984/_all_dbs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://morris-tibet.codio.io' is therefore not allowed access."
I have set-up the origins and cannot understand what the problem could be.
Here is the code I am using to connect:
myApp.controller('OverviewCtrl', ['$http',
function($http) {
var self = this;
self.dbNames = [];
$http({
url: 'http://ip:5984/_all_dbs',
method: 'GET'
}).
success(function(data, status, headers, config) {
self.dbNames = data;
console.log(self.dbNames);
}).
error(function(data, status, headers, config) {
self.dbNames = ['Something wrong with your code!', ''];
console.log(self.dbNames);
})
}
]);
In the code the ip address has been replaced for security reasons.
EDIT:
I was told it may be an issue with my CORS, here is an image showing my cors for the server:

AngularJS 'No 'Access-Control-Allow-Origin' header is present on the requested resource' error

I am using AngularJS 1.2.20.
Whenever I use the $http service to access a zip file from a URL (different domain/server), it gives me an error as following:
XMLHttpRequest cannot load http://localhost/ABC/updates.zip. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
I've tried setting the following in the config of my module:
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
But this still throws the error.
My code snippet is :
$http({method: 'GET', url: paths.categoryUpdateURL}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
alert("download Complete")
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("error")
});
What should be done to prevent this?
Unless the server provides a JSONP API, or allows configuring the Access-Control-Allow-Origin response attribute, you can't do anything besides requesting that your server requests the ZIP file, as the browser won't allow it.

Angular simple JSON request

this will probably make me look like a total beginner and I am when it comes to angular, but here's my question:
I'm trying to make a simple request to a .JSON api but I just keep getting the error status code 0.
var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2';
$http({method: 'GET', url: dataUrl}).
success(function(data, status, headers, config)
{
window.alert('success:' + status);
}).
error(function(data, status, headers, config) {
window.alert('error:' + status);
});
Update:
I checked the javascript console via the browser and got these error messages:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
Failed to load resource: the server responded with a status of 501 (Not Implemented) http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access. http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2
XMLHttpRequest cannot load http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.
You are trying to do a cross-domain request. This is forbidden by browser (it will only let you make requests to the same domain as your page was initially loaded from). This is not specific to angular, but just ajax requests in general.
You can read about it here:
http://en.wikipedia.org/wiki/Same-origin_policy
There are several ways around it, such as JSONP and CORS. Both require server-side support. You would have to look at the service you are calling to see which it might support.
You can read about how to do a JSONP request here:
http://docs.angularjs.org/api/ng.$http
You are not allowed to access resource on another website.
You need to use jsonp.
This is an un-tested modified code of yours, please try it to see whether it's working or not:
var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?jsonp=JSON_CALLBACK&limit=2';
$http.jsonp(dataUrl).
success(function(data, status, headers, config)
{
window.alert('success:' + status);
}).
error(function(data, status, headers, config) {
window.alert('error:' + status);
});
more to read:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Angular JS - can't receive any response using $http.post

I'm trying to get a response from a web service using Angular JS, which I can perfectly reach via my shell using a simple curl command:
curl --header "Content-type: application/json" --request POST
--data '{"username": "name", "password": "pwd"}' 192.168.2.1:9000/ws/login
However, when I try to reach it using Angular with an $http.post I experience some "funny" behaviour.
While my data are:
var url = "192.168.2.1:9000/ws/login"
var postData = {
username: un,
password: pwd
}
I've tried both postData as a JSON object and as a stringified JSON
Using a call like this:
$http.post( url, postData ).
success(function(data) {
console.log(data)
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config)
})
or even
$http({
url: url,
method: 'POST',
data: JSON.stringify(postData),
headers: {'Content-type': 'application/json'}
}).
success(function(data, status, headers, config) {
console.log('Success: ', data, status, headers, config)
}).
error(function(data, status, headers, config) {
console.log('Error: ', data, status, headers, config)
})
Simply do nothing.
Nothing at all!
Prepending an http:// to the url instead, gives me:
OPTIONS http://192.168.2.1:9000/ws/login 404 (Not Found) angular.js:7073
OPTIONS http://192.168.2.1:9000/ws/login Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
I'm really really lost... any advice would be much appreciated!
I've managed to get a CORS setup up & running.
The server side for my case was far from trivial, since we're using Play! framework and modern browsers sends an OPTION method before sending the real POST method, to be somewhat "pre-authorized" to send the CORS request.
As stated in http://better-inter.net/enabling-cors-in-angular-js/ I had to add
$http.defaults.useXDomain = true;
prior of the actual $http.post, but I didn't had to delete the 'Content-Type' header
Should you ever use a similar setup, I would reccomend taking a look on these resources:
Play 2.0.1 and setting Access-Control-Allow-Origin
Play! 2.0 easy fix to OPTIONS response for router catch-all?
As Adam said!
If you are using apache:
Header set Access-Control-Allow-Origin: http://domain.com, http://localhost/
or just
Header set Access-Control-Allow-Origin: *
Do this only for testing. For production limit the origin to only your domain.

Categories

Resources