passing data using AngularJS $http.get method - javascript

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" />

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 ! :)

angular-seed POST acts differently for each browser

I'm not sure what is going on with my http post method. From what I was reading, there might be something wrong with my security, but I am not really sure that is the case or how to fix it. Any insight in the right direction would be nice.
I am trying to post to an API and retrieve a response back and return the data. When I run the POST in IE, I get the proper response.
However when I try this in Chrome I get weird results. My POST turns into an OPTIONS method. With a Status Code of 200 OK, but my Response is blank. And when I try to go to the url directly without the POST I get this displayed in the browser:
{"result":false,"error":"Authentication failed: Session authentication failed: No Host Name specified Authentication State: Invalid Login"}
Here is the test.js (controller)
var host = '255.255.255.255';
var creds = {'logintype':'1','host':host,'user':'Administrator','password':'1234','controlid':'ABC999'};
//var obj = JSON.stringify(creds);
angular.module('myApp.test', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/test', {
templateUrl: 'test/test.html',
controller: 'TestCtrl',
resolve: {
friends: ['$http', function($http) {
return $http({url: 'http://192.168.2.164/ISAPI/rip.dll/REST/SESSIONS/',method: 'POST', data: creds })
.success(function (data) {
return data;
})
.error(function () {
return 'Error';
});
}]
}
});
}])
.controller('TestCtrl', ['$scope', 'friends',function($scope,response) {
$scope.response = response;
}]);
Thanks to itsananderson, I was able to resolve my issue. I was happening because Chrome does something called a "preflight" for cross-domain requests. I needed to move the API to be on the same server as the site was being run to avoid cross site scripting.

Unable to send data using POST request in AngularJS

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 :(

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

configure angularjs module to send patch request

I am totally new to AngularJs. I am trying to send a PATCH request using Angularjs to Django Tastypie API's. My code is
var module = angular.module('myApp', []);
module.config(function ($httpProvider) {
});
function MyController($scope,$http)
{
$scope.patchCall=function(){
$http({
url: "/patchrequest/",
data:data,
method: "PATCH",
})
.success(function(data){
console.log("SUCCESS");
$scope.list = data.items;
}).error(function() {
console.log("FAIL");
});
}
}
But when I am trying to send a request using this code I am Getting an error that http.patch is not a function. Tell me how can i configure ng-app and services to send a PATCH request using AngularJs. I read PATCH request is available in $resource so i tired it with $resource also. But find the same result. Please guide me how can i configure an app from scratch to send CRUD requests, specially PATCH request
Your error doesn't make sense based on the code you're showing, but a common issue with adding PATCH to AngularJS is that it doesn't have a default Content-Type header for that HTTP method (which is application/json;charset=utf-8 for PUT, POST and DELETE). Here's my configuration of the $httpProvider to add patch support:
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
}
}])

Categories

Resources