I'm use AngularJS 1.3 and CodeIgniter 3.0.
I success to GET data from php in localhost.
However I have error "Cross-origin-request blocked".
I do not know it but was a search, plese help me.
Javascript
var module = angular.module('app', ['onsen']);
module.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
module.controller('MasterController', function($scope, $http) {
$scope.doLogin = function() {
var postData = {"email": "aaa#bbb.ccc", "password": "pass"};
var url = 'http://example/test?callback=JSON_CALLBACK';
//This section is Error
$http.post(url, postData, {withCredentials: true})
.success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
//This section is Success
$http.get(url).success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
};
});
I tried "$http({url ~})", but It was the same result.
PHP
public function index() {
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$this->output
->set_header("Access-Control-Allow-Origin: *")
->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin")
->set_content_type('application/json')
->set_output(json_encode($input_data));
}
Try Using .htaccess to allow CORS. Put this in your server .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Even accessing different port is perceived by browser as cross-domain action, the best guide so far how to enable CORS can be found here http://enable-cors.org/
Related
I have a problem when you submit parameters using $ http.post in angular.
I assume it's some sort of error itself have little knowledge of angular , because in jquery work fine.
Request jquery'javascript
var user = $('#usuariotxt').val();
var pass = $('#passwordtxt').val();
var login= {
Usuario : user,
Password : pass
};
$.ajax({
type: 'POST',
url: 'http://190.109.185.138/Apipedro/api/login',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
Request Angular-Javascript
var app;
app = angular.module('AppUPC',[]);
app.controller('Formulario',['$scope', '$http', function ($scope, $http){
$scope.login = function(){
var login = {
Usuario: $scope.usuariotxt,
Password: $scope.passwordtxt
};
console.log(login);
var url, method;
url = 'http://190.109.185.138/Apipedro/api/login';
method = 'POST';
$http.post("http://190.109.185.138/Apipedro/api/login", {},
{params: {Usuario:$scope.usuariotxt, Password:$scope.passwordtxt}
}).success(function (data, status, headers, config) {
$scope.persons = data;
console.log($scope.persons);
}).error(function (data, status, headers, config) {
$scope.status = status;
console.log($scope.status);
});
};
}]);
I have also used many other forms , including the most common
$http({
url: url,
method: method,
data: login,
headers :{'Content-Type':'application/json'}
})
Errors that occur to me are the following
Short answer: If you want to send the same data as the jQuery example, use this
app.controller('Formulario', ['$scope', '$http', '$httpParamSerializer', function ($scope, $http, $httpParamSerializer) {
// snip
$http.post(url, $httpParamSerializer(login), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function success(response) {
$scope.persons = response.data;
}, function error(response) {
$scope.status = response.status;
});
}]);
This is because jQuery by default sends POST data as an x-www-form-urlencoded string, ie
Usuario=dfvides&Password=dfvids
Using the code above, Angular will send an identical request to jQuery.
Angular by default sends POST data as JSON with the Content-Type header set to application/json, ie
{"Usuario":"dfvides","Password":"dfvids"}
Is your API even set up to handle a JSON payload?
The reason your Angular version was triggering a pre-flight OPTIONS request (which it appears that your API is not equipped to handle) was because the header Content-Type: application/json makes the request non-simple...
A simple cross-site request is one that:
Only uses GET, HEAD or POST. If POST is used to send data to the server, the Content-Type of the data sent to the server with the HTTP POST request is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain.
Does not set custom headers with the HTTP Request (such as X-Modified, etc.)
this is my angular code:
samirsoftApp.controller("OrderCtrl",function($scope,$http){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.$apply(function(){
$scope.item = data;
});
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
when it request and get answer, it does not update my item object, so I used $apply and it did not work and throw an error:
Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.13/$rootScope/inprog?p0=%24digest
S/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417
.....
I also tried
$timeout(function() {
$scope.item = data;
}, 0);
instead of $apply` but it prints a null object in consol
it's like this:
samirsoftApp.controller("OrderCtrl",function($scope,$http,$timeout){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$timeout(function() {
$scope.item = data;
}, 0);
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
What should I do for my object to be updated after a http request.
thanks
You can assign the data returned by $http.get() request like this
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.item = data;
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data);
});
};
No need for $apply as angular automatically updates $scope
I suspect the problem is elsewhere with your code
Possibly:
You defined function#getItem which contained the $http request but where did you call it?
Make sure the call to URL /test/getItemDetails/ is
returning data by manually browsing or by using a utility like POSTMAN.
being called with the proper URL - try checking in developer tools > network for 404 Errors
I have updated your code - demo here - http://jsbin.com/notudebiso/1/edit?html,js,output
(using a $http call to github api)
Hello I have a simple question but I'm running into problems. I edited some code that I found on line. I'm trying to utilize an Angular http service to retrieve JSON data but it doesn't seem to be working
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
My code example is below
http://codepen.io/jimmyt1001/pen/dPVveN
You spelled wrong sucess should be success
CODE
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
you should use a service for this:
json.service('getJson', ['$http', function ($http) {
var promise = null;
//return service
return function () {
if (promise) {
return promise;
} else {
promise = $http.get('url');
return promise;
}
};
}]);
function MainCtrl($scope, getJson) {
getJson().success(function (data) {
$scope.json = data;
});
};
Remember to inject the service name in your controller.
tl;dr
It should be like this:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http)
{
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config)
{
$scope.posts = data;
})
.error(function(data, status, headers, config)
{
// log error
});
});
I.e. you're missing a dot (.) before success and your success is incorrectly typed (you type sucess).
Original
Your code should be structured like this:
// Simple GET request example :
$http.get('/someUrl').
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.
});
As explained in the docs.
Yours is like this:
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
Wherea you're missing a dot (.) before the success, and your success is spelled wrong (yours is sucess).
It's decent practice to copy existing demos until you're certain on how they're really setup. Also, use your developer tools to catch easy bugs like this.
It's also possible that your dropbox call is simply invalid, but if you fix your code accordingly then the error method should be able to catch it and you should be able to see the error.
as i am working on angular js for using the rest-full web services in my website,
but my problem is i am getting controll into error field instead of success and i stucked into it since past three days any help will be appreciated more, and this is my anguls js code.
`
function customersController1($scope, $http) {
$http({
url: 'http://localhost:9090/quote',
dataType: 'text/json',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function(data){
$scope.data = data;
alert(data);
}).error(function(error){
$scope.error = error;
alert('error');
});
}
</script>
`enter code here`<div ng-controller="customersController1">
<!-- div>{{ quotes }}</div-->
<ul>
cc <li ng-repeat="quotes"> cc{{ quotes }}</li>
</ul>
</div>`
thanks in advance friends.
First make sure the url is working by accessing it in browser and then ensure sure you are using ng-app in your html .
Next -
$http's config object doesn't have ant property 'dataType'. you can remove and try your example.
$http(
{
method : 'GET',
url : 'http://localhost:9090/quote',
}
).success( function(data, status, headers, config)
{
})
.error(function(data, status, headers, config)
{
});
or else you can even use $http's get method to for http get calls.
var config = {};
$http.get('http://localhost:9090/quote', config)
.success(function(data, status, headers, config) {})
.error(function(data, status, headers, config) {});
To know more, read - https://docs.angularjs.org/api/ng/service/$http#get
A note - content-type header is usually sent in http request header while making an POST/PUT call to specify the content type sent from client to server. In your case, you may not need the header.
To know more read - http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
So I wrote the following function, using Angular $http:
$http(
{
method: 'POST',
url: '/api/user/auth/',
data: '{"username":"alex", "password":"alex"}',
})
.success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});
I read in documentation for POST method that Content-Type header will be automatically set to "application/json".
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
This cause my API to not respond properly to this request. How should I manage this content-type?
The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.
myapp.controller("AccountController", function($scope) {
$scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it
$scope.saveAccount = function() {
users.current.put($scope.user, function(response) {
$scope.success.push("Update successful!");
}, function(response) {
$scope.errors.push("An error occurred when saving!");
});
};
}
myapp.factory("users", function($http) {
return {
current: {
put: function(data, success, error) {
return $http.put("/users/current", data).then(function(response) {
success(response);
}, function(response) {
error(response);
});
}
}
};
});
Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:
$http.put("/users/current", data || {}).then(/* ... */);
Try this;
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post('/api/user/auth/', data).success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});