angularjs how to post key/values not json object - angularjs

I hava a json object in my ctl:
$scope.disease
and anyone can edit it's properties and then post to server.
when save it,
$scope.save = function(){
$http.post('/***', $scope.disease)
}
however, the request body is as a json string.
while I want it to be as form data:
key1: value1
key2: value2
key3: value3
how can I do?
thanks a lot
after I set the Content-Type like this:
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}])
the request header:
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/x-www-form-urlencoded; charset=UTF-8
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
however the post parameter like this:
{"age":56,"birthday":"1958-07-14","familyHistory":"********************","id":1,"illness":"*********************","illnessHistory":"***************************","number":"21","selfDescription":"***********************"}
Because the $scope.disease is:
{
"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"
}
while the post parameter should like this:
"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"
Do you understand me?
Finally I add a transformRequest method to post-request:
$httpProvider.defaults.transformRequest=function(obj){
var str =[];
for(var p in obj){
str.push(encodeURICompent(p)+'='+encodeURICompent(obj[p]));
}
return str.join('&');
}
Then the problem solved!

In the $http.post call, add a correct Content-Type header to the config object (third parameter). If left empty, Angular defaults to a JSON payload.
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }

Set the Content-Type attribute of the header to application/x-www-form-urlencoded using the $httpProvider on your config or do it for each request on the $http service.

You can do it in below mentioned ways
this.createOrder = function(userId,accountId,deliveryDate,cutOffDateTime,customerRef){
var orderCreateURL = contextProp.baseURL + '/users/'+userId+'/account/orders';
return $http({
method: 'POST',
url: orderCreateURL,
data:{
'accountId': accountId,
'deliveryDate':deliveryDate,
'cutOffDateTime':cutOffDateTime,
'customerRef':customerRef
}
});
};
It will post your data in key,value pairs. You can also specify the headers i.e. headers: {'Content-Type': undefined } and transformRequest: angular.identity etc.. in parameters same as any other HTTP requests. Thanks.

Related

Why do my headers in TransformRequest become lowercase?

I have the following codes:
save: {
method: 'POST',
headers: {
'X-L5S-View-Mode': 'front',
'Content-Type': 'application/json',
'Accept-Language': ''
},
transformRequest: function (data, getHeaders) {
console.log(resource.lang);
var headers = getHeaders();
headers['Accept-Language'] = resource.lang;
console.log(headers);
return JSON.stringify(data);
}
}
in my resource factory.
Weirdly, all my headers are converted to lower case.
Here's the log:
fr <-- resource.lang
Object {x-l5s-view-mode: "front", content-type: "application/json", accept-language: "", accept: "application/json, text/plain, */*", Accept-Language: "fr"…} <-- headers
Why are my headers in lower case?
Plus, when I inspect with Chrome, I found that the Accept-Language is blank. So even I have changed the Accept-Language with headers['Accept-Language'] = resource.lang;, it doesn't work at all.
Because the latest version of Angular do not support this way to modify the headers anymore.
Angular 1.3.20 works for me.
Just change the version of Angular in bower.json, delete the original Angular, then cd to your directory and run bower install.

Angularjs login with headers Authentication

$http({
url: 'https://www.test.com/user/Api/Securelogin',
method: "POST",
header: {
access_token : 'jjyzstmozj75',
client_id : 'll_123_APP',
client_secret : 'sdfxilxxsfd'
},
data : {
username: username,
password: password
}
}).success(function(response) {
callback(response);
});
What I would like to get
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate, br
Accept-Language en-US,en;q=0.5
Authorization Basic This place need to be changed
Content-Length 36
Content-Type application/json;charset=utf-8
Cookie PHPSESSID=b5b7a9d95cD
Host www.test.com
Referer https://www.test.com/newclip/
User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
access_token sdfsdfb9clyzsosdfsd
client_id ll_123_APP
client_secret dfgdf6j1l2dxsdf
What I get instead
NetworkError: 401 Unauthorized
It is posting username password as json.
source :
{
"username" : "abc",
"password" : "4214"
}
Response is
{
"username" : [
"username or email cannot be blank."
],
"password" : [
"password cannot be blank."
]
}
What kind of issue is this?
Try this.
$http.post('URL', { headers: {"Accept": "application/json","Content-Type": "application/json",'authorization': 'Basic eyJhbGciOiJIUzI1NiIsInR5c'} ,
params: {
username: username,
password:password
}
}).then(function(response){
});
Use this
$http({
"method": "GET",
"url":url + "",
"data": data,
"headers": { 'Authorization': '34444344444},
"Content-Type": "application/x-www-form-urlencoded ; charset=UTF-8"
})

AngularJS $http date header

I'm trying to retrieve the $http date header from an AngularJS $http.get request so I can get the server time.
app.controller('MainCtrl', function($http,$scope) {
$scope.name = 'World';
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
console.log(response);
})
});
I can't seem to retrieve the Date header although when I inspected on chrome tools the date header was there.
try this:
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
var data = response.data,
status = response.status,
headers = response.headers(),
config = response.config;
})
headers will contain:
headers: {
"date": "Mon, 02 Mar 2015 23:02:51 GMT",
"content-encoding": "gzip",
"server": "Apache",
"vary": "Accept-Encoding",
"content-type": "text/html",
"connection": "Keep-Alive",
"keep-alive": "timeout=10, max=500",
"content-length": "39"
}
to access date:
headers.date
Since it's a CORS request to facebook api: The response header will contain only
Content-Type
Last-modified
Content-Language
Cache-Control
Expires
Pragma
The issue is because of missing Access-Control-Allow-Headers from request Header. To fix this we need to add Access-Control-Allow-Headers: * to request header in your run method

AngularJS $http post fails

I am new to AngularJS, I am from SAP background and as part of my PoC I built my REST services using SAP NW Gateway,I am facing an issue to POST data from Angularjs to my REST services.Please find the below detailed error log
***1. Remote Address:
10.xxx.xx.xx:8000
2. Request URL:
//host:port/sap/opu/odata/sap/USERS/Users
3. Request Method:
POST
4. Status Code:
400 Bad Request
5. Request Headersview source
1. Accept:
application/json, text/plain, */*
2. Accept-Encoding:
gzip,deflate
3. Accept-Language:
en,te;q=0.8
4. Authorization:
Basic a2VsYW1yOmoyZDEwMA==
5. Connection:
keep-alive
6. Content-Length:
146
7. Content-Type:
application/json;charset=UTF-8
8. Cookie:
sap-usercontext=sap-client=100; SAP_SESSIONID_J2D_100=R_60WyUyNG2nV1MbhC9QAcKPzyBwwxHkmwsAUFaDBqQ%3d
9. Host:
abcdefgh:8000
10. Origin:
file://
11. User-Agent:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
12. X-CSRF-Token:
_jXDnt2Cdpplpj5zvK3iPA==
6. Request Payloadview source
{UserID:555, FirstName:rajesh555, LastName:kelam555, Email:rajesh555#gmail.com, Phone:9876554433,…}
1. Country: "UK"
2. Email: "rajesh555#gmail.com"
3. FirstName: "rajesh555"
4. LastName: "kelam555"
5. Phone: 9876554433
6. Postcode: "TW18 4BL"
7. UserID: 555
7. Response Headersview source
1. content-length:
535
2. content-type:
application/json
3. dataserviceversion:
1.0****
Angular Code for Post :
$scope.addRow = function () {
var config = {};
var pushdata = {'UserID':$scope.UserID, 'FirstName':$scope.FirstName, 'LastName':$scope.LastName, 'Email':$scope.Email, 'Phone':$scope.Phone, 'Country':$scope.Country, 'Postcode':$scope.Postcode};
// Sending Notification to User
growl.addSuccessMessage("User Created", config);
/* $http.post(url,pushdata, {'Content-Type':'application/json'}).success(function(pushdata) {
$scope.resultSet = pushdata.d.results;
alret("Data Posted");
}) */
$http.post(url,pushdata, {headers:{'Content-Type':'application/json'}}).success(function(data){alert(data);});
$scope.resultSet.push(pushdata);
$scope.createMessage();
$scope.UserID='';
$scope.FirstName='';
$scope.LastName='';
$scope.Email='';
$scope.Phone='';
$scope.Country='';
};
it would be great if some one help me to sort.
*Note: I am a kid in AngularJS...please ignore me and feel free to thought me.
I request to suggest the best URl/Site to learn Angularjs in a better and consistent way.
I thought, if I share the format(XML/JSON) of payload expecting for the POST to perform by my SAP Gateway service which will helps me to quickly resolve this.Below are the formats of XML/JSON works for POST.
XML Format:
host:port/sap/opu/odata/sap/USERS/Users('123')
Users('123')
2014-11-21T15:21:52Z
123
RAJESH
KELAM
RAJESHKUMAR.KELAM#ABG.CO.UK
123456789
UK
RG4 6SA
JSON Format:
{
d:
{
__metadata:
{
id: "host:port/sap/opu/odata/sap/USERS/Users('123')"
uri: "host:port/sap/opu/odata/sap/USERS/Users('123')"
type: "USERS.User"
}
-
UserID: "123"
FirstName: "RAJESH"
LastName: "KELAM"
Email: "RAJESHKUMAR.KELAM#ABG.CO.UK"
Phone: "123456789"
Country: "UK"
Postcode: "RG4 6SA"
}
-
}
You sure that the url you posting is expecting this data you want to post? You can use POSTMAN extension (in google chrome) and test if you service are ready to receive any data from http.post
Finally I could able to sort out my problem, it is all about formatting the data passing to REST service..
below is the peice of code which works is my case
$scope.addRow = function () {
var StrUId = ($scope.UserID).toString();
var StrPh = ($scope.Phone).toString();
var pushdata = {"UserID":StrUId, "FirstName":$scope.FirstName, "LastName":$scope.LastName, "Email":$scope.Email, "Phone":StrPh, "Country":$scope.Country, "Postcode":$scope.Postcode};
// Posting data
$http({
method: "post",
url:url,
data:pushdata,
headers: {
"X-CSRF-Token": "0XGo8HzpzrhaZxxX83QH9g==",
},
dataType : "json",
async: false,
contentType: 'application/json',
success: function(data){
alert(data);
}
});
Thanks for the support given
Rajesh

AngularJs Service, File Upload, Laravel

I'm having trouble with an XHR Request, for some reason my server is not receiving my files:
Here is my angular service update algorithm:
var update = function(id, name, file) {
var formData = new FormData();
formData.append('name', name);
formData.append('img', file);
return $http({
method : 'PUT',
url : '/albums/' + id,
data : formData,
headers : {'Content-Type': undefined},
transformRequest : angular.identity
});
};
On my laravel controller I just have:
public function update($id) {
return Response::json(Input::hasFile('img'));
}
The file is obviously there, why can't I retrieve it in my backend?
This is my request info:
Remote Address:[::1]:8000
Request URL:http://localhost:8000/albums/1
Request Method:PUT
Status Code:200 OK
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:13811
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryJ46EVSBw57RaVu7x
Cookie:_token=eyJpdiI6IkkzSXVmdnhubFFlVnlzSnZNWVFzVWk3ZlVKSFRDNFFlNndJWUVsVGNVU2c9IiwidmFsdWUiOiI5OG5PamUrVGZkZGx0ajZONklWajJ2OTM3MWlRd2tGZ2g5S2Jja1RhVjJ4Q1wvYk9xQTB4TlRKUWxkWmdvRm1EcHlzTGRjSEdzN2U5TWNPYWxEYVExVUE9PSIsIm1hYyI6IjA4NTY0ZTlmMjAyNTk3NGQxMmFhODIxMTU3NGNiYjQ4ZDA3OTgxMTA3Yzk1MmVkNmJkMGNkYjUyMmNhMzZkNzQifQ%3D%3D; laravel_session=eyJpdiI6IjRISElnWjd3ZlwvY2k1Z1pvOERWOGxyVHlaQzEwRmlqY1FiV0tNNzZEbEs4PSIsInZhbHVlIjoiYnp4UzVqOFoxMm5MMXhQdzJhVFphSkgrRGh2b2plYXhjdXpTamJ0UjVYdGdxS0puQmpPVXhObEtyb1I3XC9HQnRFdnBMWXV0MzRmWXAybGRySGRvXC9vUT09IiwibWFjIjoiMGQ1NzUyYTBjZmU3NzQ3ZDBkYjg5ZWViOGZmYzg3ZDY1ODg0N2JmNDg1NmQyNmMwZDcxMDE5NzcxZjIxM2MxMiJ9
Host:localhost:8000
Origin:http://localhost:8000
Pragma:no-cache
Referer:http://localhost:8000/Admin/Client
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
Request Payload
------WebKitFormBoundaryJ46EVSBw57RaVu7x
Content-Disposition: form-data; name="name"
Some Weird Album
------WebKitFormBoundaryJ46EVSBw57RaVu7x
Content-Disposition: form-data; name="img"; filename="derpino.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryJ46EVSBw57RaVu7x--
Response Headers
Cache-Control:no-cache
Connection:close
Content-Type:application/json
Date:Wed, 29 Oct 2014 12:47:20 GMT
Host:localhost:8000
Set-Cookie:laravel_session=eyJpdiI6IlQ4WlFOaG1keVhXVlA1dlluNWFZZGlMcmRQNGM3bThCRjZ6cnh4ZlorcWs9IiwidmFsdWUiOiJOZkJXNXBJQTVSTGZzWHJ4alg1SXBoN0Q2ekR6UVpnWThKQ0c4MXZOQlc1RUhNMUUraUZSTlpPYTlPTFdLQXpiYTJONkRvb29WN1djVlZkSGdaWStjQT09IiwibWFjIjoiOWI5MzEwODE2YTZlM2EzODMwZDE1YzI4YmE4M2NiYWJjMTRjMDEzOGI3YjA4NmRlMGU5NDBlZWEyMzI4MGQ3MCJ9; path=/; httponly
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.5.11
I found the error! Apparently I can not send a file with the PUT method, I changed the method to POST and It works. In both the service and the laravel route
var update = function(id, name, file) {
var formData = new FormData();
formData.append('name', name);
formData.append('img', file);
return $http({
method : 'PUT',
url : '/albums/' + id,
data : formData,
headers : {'Content-Type': undefined},
transformRequest : angular.identity
});
};

Resources