i have a problem sending my angularJS POST parameters to my nodejs server... i've seen many topics related to this, tried everything here and nothing works (there were more):
How to pass parameter in Angularjs $http.post
Angular: how to pass $scope variables into the Node.js server.
How to pass client-side parameters to the server-side in Angular/Node.js/Express
How to pass data from AngularJS frontend to Nodejs backend?
my relevant code that is envolved in this problem,
handlebars-template:
<div ng-controller='questions'>
<form method="POST" class="form-inline" class="my-search-menu">
<button ng-click="search()" class="btn btn-default glyphicon glyphicon-search" type="submit" style="background-color: #85C1E9;"></button>
<input style="direction: rtl" type="text" name="search_text" ng-model="search_text" class="form-control" placeholder="Search" aria-describedby="sizing-addon3">
</form>
</div>
AngularJS:
var myapp= angular.module('myapp', []);
myapp.controller("questions", function($scope,$http) {
$scope.search = function () {
var formdata = {search_text : $scope.search_text};
$http.post('/search', {params: formdata})
.success(function (data, status, headers, config) {
$scope.questions = data;
})
.error(function(data, status, header, config){
$scope.onerror = "Data: " + status;
});
console.log(formdata);
};
});
NodeJS:
app.post('/search', function (req,res,next){
var search_text = req.query.params.formdata.search_text;
console.log(req);
Question.find({$text: {$search: search_text}}).exec(function (err, questions){
res.json(questions);
});
});
There are few points you are missing. First in the anguar controller
$http.post('/search', {params: formdata})
will send {params:formdata} as request body in the node server.. So in the server end you will receive the data as request.body. correct way to receive the body in this case will be ..
app.post('/search', function (req,res,next){
var search_text = req.body.params.search_text;
//TODO
});
If you want to send the data as parameter then in controller write the function like this...
$http({
method: 'POST',
url: '/search/'+paramData,
}).then(function successCallback(response) {
//TODO
}, function errorCallback(error) {
//TODO
});
And in the server side...
app.post('/search/:searchText', function (req,res,next){
var paramData = req.params.searchText;
//TODO
});
Related
I keep getting a 405 error when trying to submit my form. Here's my controller:
'use strict';
angular.
module('myApp').
component('zipPopup', {
templateUrl: 'zip-popup/zip-popup.template.html',
controller: function ZipPopupController($scope, $http) {
$scope.show = true;
$scope.hide = function(){
$scope.show = false;
};
$scope.user = {};
$scope.regex = '\\d{5}';
$scope.submitForm = function(isValid) {
if(isValid) {
$http({
method : 'POST',
url : '/leads',
data : $scope.user,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.show = false;
})
.error(function(response) {
console.log(response);
});
}
};
}
});
Heres my view:
<div class="zip-popup text-center">
<div class="popup-container">
<form name="zipForm" class="zip-form" ng-submit="submitForm(zipForm.$valid)" novalidate>
<input ng-model="user.zipCode" ng-pattern="regex" name="zipCode" class="form-control text-center" placeholder="Your Zip" required />
<p class="error" ng-show="zipForm.zipCode.$invalid && !zipForm.zipCode.$pristine">A 5 digit zip code is required.</p>
<button type="submit" class="btn btn-block" ng-disabled="zipForm.$invalid">Submit</button>
</form>
</div>
</div>
Is there a different file or something that I need to modify to allow this to happen? What am I missing?
The server is telling you that the particular method (GET, POST, PUT, PATCH, DELETE, etc.) can't be accepted by the server. This is most likely due to the fact that your API route/endpoint doesn't have a POST method configured.
For example, in ExpressJS you'd need to configure a route that accepts POST by doing the following:
app.post('/leads', function (req, res) {
res.send('POST request to the homepage');
});
For more information on the 405 Method Not Allowed error, click here.
I had a similar issue a couple of weeks ago. It turns out that the server was only accepting 'Content-Type' of a particular type in the headers.
However changing the Content-Type to application/json solved the issue:
$http({
method : 'POST',
url : '/leads',
data : $scope.user,
headers : {'Content-Type': 'application/json'}
})
.success(function(response) {
$scope.show = false;
})
.error(function(response) {
console.log(response);
});
P.S. I'm not saying this will necessarily solve your issue, but this is a solution related to this type of problem. Just find out what kind of input your server is expecting.
EDIT
I'm not saying to send 'application/json' as the Content-Type. All I'm saying is that Find what type of content is acceptable and send that type of header.
you try to let the back-end engineer to implement the OPTIONS method.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Preflight_example
I need one help.I need to retrieve the data present in body part of a URL using Angular.js.I am explaining my code below.
var app=angular.module('hello',[]);
app.controller('Hello',function($scope, $http){
$http.get('http://oditek.in/medilink_global_new/#/product/Api/apiCatagory').
success(function(data) {
console.log('data',data);
$scope.greeting = data;
});
});
In console message i need the required json data.
The controller function of http://oditek.in/medilink_global_new/#/product/Api/apiCatagory is given below.
var cat=angular.module('medilink');
cat.controller('apiCatagoryController',function($state,$http,$scope){
$http({
method:'GET',
url:"php/category.php?op=disp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
//console.log('catagory',response.data);
$scope.catadata=response.data;
},function errorCallback(response) {
});
})
catagory.html:
<div>
{{catadata}}
</div>
route.js:
.state('api',{
url:'/Api',
templateUrl:'Apiview/api.html',
controller:'apiController'
})
.state('api.catagory',{
url:'/apiCatagory',
templateUrl:'Apiview/catagory.html',
controller:'apiCatagoryController'
})
index.html:
<div ui-view>
</div>
Here inside body part i am displaying the ($scope.catadata) DB values.I need when any user will call this URL to get the data the data will deliver to the user.Please help me.
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.)
I tried to get api response for "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA" using angularjs $http .get method and $http.JSONP method. But it doesnt work properly it returns nothing. When i tried this api via REST client and browser , it provides the JSON data with status code 200.
Here is my code ...
index.html
<html ng-app="myApp">
<body ng-controller="MyCtrl">
<button ng-click="getlocation()">Get Location</button>
</body>
</html>
app.js
var app = angular.module('myApp',[]);
app.controller('MyCtrl', ['$scope','$http',function ($scope,$http) {
$scope.getlocation=function(){
$scope.method = 'JSONP';
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA"}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
alert(JSON.stringify(data));
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert($scope.data+$scope.status);
});
}
}]);
while run this code in browser it returns nothing. Throws error.
Could you please help me to get out from this problem??
to work with jsonp in angular, you need... ?callback=JSON_CALLBACK passed to the get call..
e.g.
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA&callback=JSON_CALLBACK"}).
read more about it here
The only problem your code has is that there isno such HTTP method as JSONP. In your case you need GET. So use this instead:
$scope.method = 'GET';
Demo: http://plnkr.co/edit/I6qAMbsvLwM3vgZFQa0S?p=preview
you have to change your request method from JSONP to GET.
$scope.getlocation=function(){
$scope.method = 'get';
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA"}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
alert(JSON.stringify(data));
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert($scope.data+$scope.status);
});
}
I have tested it from my side and its returns
Object {results: Array[1], status: "OK"}
Hope you get what you are looking for.
I'm having a problem getting $http.post to fire:
app.controller('editPageController', function($scope, $routeParams, $http) {
$scope.page = $routeParams.pageid;
// get page data from server
$http.get('/pages/' + $scope.page).
success(function(data, status, headers, config) {
$scope.Name = data[0].name;
$scope.Content = data[0].content;
$scope.Location = data[0].location;
}).
error(function(data, status, headers, config) {
alert("Can't get the page from the server");
});
// save page data on the server
$scope.saveEditPage = function() {
var postOBject = {Name: $scope.Name, Content: $scope.Content, Location: $scope.Location};
$http.post('/pages/' + $scope.page + '/edit', postObject).
success(function(data, status, headers, config) {
alert("success");
}).
error(function(data, status, headers, config) {
alert("Can't edit the page on the server");
});
};
});
The template code:
<script type="text/ng-template" id="editPage.html">
<h1>Edit page:</h1>
<form ng-submit="saveEditPage()">
<p>Name:</p>
<input type="text" ng-model="Name" value="{{Name}}">
<p>Content:</p>
<textarea ng-model="Content">{{Content}}</textarea>
<p>Location:</p>
<input type="text" ng-model="Location" value="{{Location}}">
<p><input type="submit" value="Save"> <input type="button" value="Cancel" ng-click="$back()"></p>
</form>
Unfortunately the $http.post does not fire. I tried wrapping the post call around $scope.$apply and it didn't work either.
How can I fix this?
Thanks
EDIT: FIXED
JavaScript variable names are case sensitive. You have declared postOBject but you are passing postObject.
ReferenceError: postObject is not defined
If I correct the typo, it's working as expected for me.
BTW I recommend using IDE with static analysis - it will inform you about undefined variables immediately. Also Firebug or Chrome DevTools javascript console are almost absolutely necessary for javascript development.