CouchDB XMLHttpRequest Error - javascript

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:

Related

angularJS sending OPTIONS instead of POST

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

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.

cross origin request error with angularjs 1.2.6

I am trying to make a simple POST request to http://battle.platform45.com/register The server is setup to respond with JSON. So from the command line:
$ curl --data '{"name": "Connor", "email": "connorleech#gmail.com"}' http://battle.platform45.com/register
successfully returns
{"id":"3118","x":1,"y":9}%
I try to do the same thing in angular:
app.controller('BattleshipCtrl', function ($scope, $http) {
$scope.game = {}
$scope.newGame = function(name, email){
$http.post("http://battle.platform45.com/register", {
name: name,
email: email
}).success(function(data, status, headers, config){
console.log('Success')
})
}
});
with a simple view:
<input type='text' ng-model='game.name'>
<input type='text' ng-model='game.email'>
<div class='btn btn-success' ng-click='newGame(game.name, game.email)'>New game</div>
When I try to make the request I get an error:
OPTIONS http://battle.platform45.com/register 404 (Not Found) angular.js:7962
XMLHttpRequest cannot load http://battle.platform45.com/register. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:9000' is therefore not allowed access.
How does the POST request go through with curl but not angular? What can I do to successfully make the request with angular?
I believe battle.platform45 is not allowing web browsers to do direct calls to their servers. By default, websites from different domains cannot access API resources from other websites.
As according to platform45, you must use Rails to create a game. So I suggest creating your own server that will call from their API server. Then use your AngularJS code to access your server.
I hope this diagram can illustrate it better:
Battle.platform45 Server -- (is called by) --> Your Server -- (is called by) --> Your HTML/Angular JS Code
Try doing this:
var config = {headers: {
'Access-Control-Allow-Origin': '*'
}
};
app.controller('BattleshipCtrl', function ($scope, $http) {
$scope.game = {}
$scope.newGame = function(name, email){
$http.post("http://battle.platform45.com/register", config, {
name: name,
email: email
}).success(function(data, status, headers, config){
console.log('Success')
})
}
});

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