I have created a basic angular $http.post request to receive some data. In order to receive the data I need to provide a key in the header.
The server is responding that the key is missing even though I've explicitly sent it.
100% it's not the server because I used an online curl tool which provided the required response.
$http.post(url, {
data:{username: username,password: password},
headers:{'Content-Type': 'application/x-www-form-urlencoded','key': key},
})
.then(function(response){
console.log(response)
})
It would be appreciated if someone could spot what I'm doing wrong here. Thanks.
You have a trailing comma after the headers key, perhaps this is throwing things off?
$http.post(url, {
data:{username: username,password: password},
headers:{'Content-Type': 'application/x-www-form-urlencoded','key': key}, // Remove this comma
})
.then(function(response){
console.log(response)
});
According to docs should be:
Shortcut method
$http.post('http://localhost:9191/api/signin', {
username: 'some username',
password: 'some password'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'key': '123'
}
})
.then(function(response) {
console.log(response)
});
Long version
$http({
method: 'POST',
url: 'http://localhost:9191/api/signin',
data: {
username: 'some username',
password: 'some password'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'key': '123'
}
}).then(function(response) {
console.log(response)
});
Tested and is working fine.
Related
I'm trying to post data from my form to an API on another domain. Request body comes back empty.
When I go to devtools, payload shows as [object Object]
I tried setting different headers like 'Content-Type' : 'application/json' or undefined but had no luck
CODE
$scope.form
{
"name":"Test",
"email":"test#test.com",
"companyName":"company",
"companySize":"6 - 10 employees",
"manageTimeOff":true
}
submit function
$scope.submitForm = function () {
$scope.success = false;
$scope.loading = true;
$http({
url: url,
method: 'POST',
data: $scope.form,
withCredentials: false,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
transformRequest: angular.identity
}).then(function (response) {
console.log(response);
$scope.loading = false;
if (response.data.Error) {
$scope.success = false;
swal("Something's gone wrong ☹", response.data.Error, "error")
} else {
$scope.success = true;
swal({
title: "Form Submitted",
text: "We look forward to speaking with you soon!",
icon: "success"
});
$scope.resetForm();
}
});
}
Content type x-www-form-urlencoded is obsolete. Design backends to use content type application/json which the AngularJS framework supports by default.
$http({
url: url,
method: 'POST',
data: $scope.form,
withCredentials: false,
̶h̶e̶a̶d̶e̶r̶s̶:̶ ̶{̶ ̶"̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶"̶:̶ ̶"̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶x̶-̶w̶w̶w̶-̶f̶o̶r̶m̶-̶u̶r̶l̶e̶n̶c̶o̶d̶e̶d̶"̶ ̶}̶,̶
̶t̶r̶a̶n̶s̶f̶o̶r̶m̶R̶e̶q̶u̶e̶s̶t̶:̶ ̶a̶n̶g̶u̶l̶a̶r̶.̶i̶d̶e̶n̶t̶i̶t̶y̶
}).then(function (response) {
//...
});
This works for me
// default post header
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// send login data
$http({
method: 'POST',
url: 'abc.php',
data: $.param({
email: "abc#gmail.com",
password: "password"
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data, status, headers, config) {
// handle success things
}).catch(function (data, status, headers, config) {
// handle error things
});
This does not
$http.post('abc.php', {email: "abc#gmail.com",
password: "password"})
.then(function(res){
$scope.response = res.data;
})
Hi could you please elobrate why first implementation is working second doesn't. I'm very confused with short cut and long cut angular method
Thanks in advance
Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively.
$http.post is transmitting your data as Content-Type: application/json
Change the header to URL Encoded as below :-
$http.post("abc.php", requestData, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
}).success(function(responseData) {
//do stuff with response
});
The second snippet should like this
$http.post('abc.php', {email: "abc#gmail.com",
password: "password"})
}).then(function(res){
$scope.response = res.data;
});
I am trying to create post request with angularjs. This is my code for adding an supplier to server.
SupplierService.addNewSupplier = function(supplier) {
alert (supplier.name);
alert (supplier.mobile);
var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
//var Indata = {'product': $scope.product, 'product2': $scope.product2 };
var req = {
url: SupplierURL,
method: 'POST',
params: Indata,
headers: {'Content-Type': 'application/json'}
};
//$http.post(SupplierURL, Indata)
$http(req)
.then(function(success){
console.log(success);
//SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
supplier.name = "";
supplier.mobile = "";
},function (error){
console.log(error);
alert ('Supplier add error.');
});
};
After making the request, callback is coming to error part and in console log i can see.
{error: true, message: "Failed to create supplier. Please try again", name: null, mobile: null}
Why name and mobile is not reaching to server. Same request works fine with postman(api testing tool). So i don't thing there can be anu issue in server side code. Any help will be appreciated.
From the $http documentation you can clearly see request parameters:
https://docs.angularjs.org/api/ng/service/$http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
So, in your case you need to switch params with data:
var req = {
url: SupplierURL,
method: 'POST',
data: Indata,
headers: {'Content-Type': 'application/json'}
};
I am trying to access this REST API, which accepts three parameters:
stationId, crusherId, monthYear
I am doing it like this in AngularJS as:
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
//headers: {'Content-Type': 'application/json; charset=UTF-8'},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'https://myurl../api/getHPData',
method: 'POST',
data: {
stationId: 263,
crusherId: 27,
monthYear: '2016-4'
}
})
.then(function(data, status, headers, config) {
//console.log(JSON.stringify(response));
console.log(data);
})
.catch(function(error){
//console.log("Error: " + JSON.stringify(error));
console.log(error);
})
But I am always getting this:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
OR
{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded;
charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}
If I change header Content-Type to:
headers: {'Content-Type': 'application/json; charset=UTF-8'},
It gives:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
OR
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json;
charset=UTF-8","Accept":"application/json, text/plain,
/"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}
What I am doing wrong, Please help me.
Plunker is here:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(Edit)
Note:
I can do it in jQuery as:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl../api/getHPData";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST
"https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is perfect. :)
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
The DEMO on PLNKR
The documentation says that the stationId and crusherId parameters should be arrays of strings. Also, it looks like you are sending JSON data, so make sure to set that header correctly.
$http({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
data: {
stationId: ['263'],
crusherId: ['27'],
monthYear: '2016-4'
}
})
When I change the code in your plunkr to use the corrected code above, I get the following response: "The requested resource does not support http method 'OPTIONS'."
As the other (now deleted) answer correctly mentioned, this means that there is a CORS issue. The browser is trying to send a "preflight" request before making the cross-origin request, and the server doesn't know what to do with it. You can also see this message in the Chrome console:
XMLHttpRequest cannot load
https://fnrc.gov.ae/roayaservices/api/getHPData. Response for
preflight has invalid HTTP status code 405
This is my code:
$scope.doLogin = function() {
$http({
method: "POST",
url: "http://localhost:8000/api/v1/user/user_signin",
data: { username: $scope.user.username, password: $scope.user.password },
headers: { 'Content-Type': 'application/json' },
responseType:'json'
}).success(function (data) {
console.log('data success');
console.log(JSON.stringify(data));
})
.error(function(data, status, headers,config){
console.log('data error');
});
};
Consol says:
data success
null
What I do wrong?
P.S.: API request is correct - I checked it in postman.
You set responseType to 'json' make sure that your server side is also sending the response compatible to your format 'json'.
Or simply remove the response type check if it works