Reputation: 453
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
Upvotes: 1
Views: 1619
Reputation: 164766
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
orPOST
. IfPOST
is used to send data to the server, theContent-Type
of the data sent to the server with the HTTP POST request is one ofapplication/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
.- Does not set custom headers with the HTTP Request (such as
X-Modified
, etc.)
Upvotes: 3