Unable to send data using POST request in AngularJS - javascript

I try to post data from angularJS to my web-Service and want to get data back.
The post-request works great, I get data back (which I hardcoded in PHP), but (after 2h searching) my problem is that I cant send some Post-Data.
Here my code:
angular.module('LunchApp', [])
.controller('MessagesCtrl', function($scope, $http){
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
var postData = { callMethod: 'getChat' };
$http.post(url, postData).success(function(data){
$scope.messages = data;
});
});
I have tried many solutions:
https://www.youtube.com/watch?v=vs-egO-odAg
How do I POST urlencoded form data with $http in AngularJS?
$http post in Angular.js
but nothing works for me... :(
If I try it with a RESTful TestClient, it works perfectly. all posted data reach the server. But not with AngularJS :(

Related

Ionic post data to server

I found this solution here, but it doesn't explain a lot so I can modify it to my needs. He is also mentioning a stack overflow question, but there are so many "different" solutions and I got confused.
The controller:
.controller('AppCtrl', function($scope, $http) {
$scope.data = {};
$scope.submit = function(){
var link = 'http://app.domain.com/api.php';
$http.post(link, {username : $scope.data.username}).then(function (res){
$scope.response = res.data;
});
console($http.post(link, {username : $scope.data.username}));
};
});
I would like modify it and add another field, so it would be username and password. and post the to the server. But the response I need it to be just one field.
Can someone give me an explanation, of the code above so I can modify it?
As NNR said, you can pass some other parameters in your HTTP request and then POST it to the endpoint of your choice (here, the link, generally an API endpoint) by submitting it through an ng-submit. The request contains your parameters and is parsed into json that you can un-parse later in your php file (in order to get params of the request and then use it in your mysql query (generally..). After the request has been sent, it will return you a promise, that will either be a success or an error based on the reply of your server, like this :.then(function success(response) { //do stuff here},
function error(response) {//do stuff here});
You will be able to access that response.data object in your controller by using $scope
I've some hard time being clear but I hope that helps ! I suggest you to have a look at https://docs.angularjs.org/api/ng/service/$http ! :)

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

passing data using AngularJS $http.get method

I'm building an application using the MEAN stack that would make use of data retrieved from an external API. As a measure to hide the API key, I want to make the API request from the server, however I am having problems passing the search term from the Angular front-end to the server.
The code below is part of the Angular controller, which should pass the request to the server with the search term:
myApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.submit = function(){
$location.path('/results');
$http({method: 'GET', url: '/makeSearch', data: {term: $scope.term} });
}
}]);
and then the following server code would parse the request using the body-parser middleware:
app.get('/makeSearch', function(req, res) {
console.log("I received a command!");
console.log(req.body); });
However once I try to pass/submit a search term from the front-end, I get only an empty object on the server console. Any tips on what I'm doing wrong? Any help would be appreciated.
I figured it out! #Rikky made a good point that the body of a http get request (req.body) is always empty. So by logging just the req to the console, I worked out how the search term can be sent using the GET method
Using params instead of data in the request within the AngularJS controller show in the code below:
revApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.submit = function(){
console.log($scope.term);
$location.path('/results');
$http({method: 'GET',
url: '/makeSearch',
params: {term: $scope.term}
});
} }]);
and on the server, logging req.query instead of req.body as shown in the code below:
app.get('/makeSearch', function(req, res) {
console.log("I received a command!");
console.log(req.query); });
Thanks for the help guys!
There are some http basic that you should know first, then you'll know what you are doing, then, you'll know how to do it right:
With HTTP GET method means querying for data, not sending data. Because of that, an HTTP request with GET method will not have body, so
request.body
will always be empty.
If you really want to send some data to the server, using POST is preferred.
If you still want to send data to the server via get, using query string is the best option. You can check it out at this question
If you want to send some data to the server via get method, but you don't want using query string, you can do some hack with http header instead of http body.
Make sure you have a term property in your scope.
myApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.term ='';
$scope.submit = function(){
$location.path('/results');
$http({method: 'GET', url: '/makeSearch', data: {term: $scope.term}
});
}
}]);
Make sure that your UI has an element which is bound to the term property of your scope
<input type="text" ng-model="term" />

Angular $http request in the controller does not work

I have the following controller. It works all fine (it parses the data and sends them into the view). The only problem I have is that it does not send $http request. Here is the code block of controller (i just send a test $http without any value from the view just to test it works or not, which does not work):
(It's also worth mentioning that I check via browser's console to see if any ajax request is sent or not)
// Controller
LoginApp.controller("RegisterController", function($scope, $http, registerService){
var username = null;
var password = null;
$scope.registerSubmit = function(){
username = $scope.register.username;
password = $scope.register.password;
};
//registerService.CheckUser();
$http.post('server.php', {name : 'something'})
.success(function(data, status, header, config){
return data;
})
.error(function(data, status, header, config){
return data;
}); // end of $http request
});
EDIT: I have edited what #JoshBeam has recommended, passing data to the post(), but it does not change anything.
You need to pass data along with the HTTP request. According to the AngularJS documentation, it is in this format: post(url, data, [config]);
Thus:
$http.post('server.php', /* your data */);

Request header field Content-Type is not allowed by Access-Control-Allow-Headers AngularJS

I am working on an API module that makes CORS requests to the service endpoint:
https://github.com/gigablox/angular-blitline-api
See the demonstration here:
http://plnkr.co/FjnJbHQHG5MM7P0VbtV6
You will notice when the API call is made I receive the following error message:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers
I've open sourced a few of these API modules before for --- Imgur, Mandrill, and Blogger --- but this is the first time I've ever seen this problem using Blitline.
Is there an issue in my code or does the service provider not like the way the request is being sent to them because of some AngularJS $http convention?
I was able to find a related topic however the solution provided did not work.
delete $httpProvider.defaults.headers.common['X-Requested-With'];
Feel free to try it with that plunker --- I should note I am using 1.1.5
Update
Your plnkr worked for me... sort of. I get the following response:
{"results":"Sorry, 'json' key expected in post data. For example { \"json\": \"{...}\" }. Please check the Blitline examples."}
According to the docs:
A job is a collection of 1 or more functions to be performed on an
image. Data submitted to the job api must have a key of "json" and a
value that is a string. The string must contain properly formatted
JSON.
You should be submitting your POST in a format like this:
angular.module('myApp', ['blitline'])
.config(['$blitlineGlobalProvider', function($blitlineGlobalProvider) {
$blitlineGlobalProvider.options({
json: '{"application_id": "YOUR_ID","version": 2,"src": "http://cdn.blitline.com/filters/boys.jpeg","functions": [{"name": "resize_to_fit","params": {"width": 240,"height": 140},"save": {"image_identifier": "external_sample_1"}}]}'
});
}])
.controller('blitlineTest', ['$scope', '$blitlineJob', function($scope, $blitlineJob) {
var blitlineJob = $blitlineJob.blitlineJob();
blitlineJob.job(function(job) {
console.log(job);
});
}]);
Here is an updated plnkr: http://plnkr.co/edit/qV7sEf?p=preview
Bitline has a working example on their site You can see it here:
http://www.blitline.com/docs/sample

Categories

Resources