I'm using $http on angularjs, and I have a fairly big request to send.
I'm wondering if there a way to do something like this:
content = "I'm a very long content string!"
$http.post content, url, 'gzip'
and have the post request content auto-gzipped and add an appropriate request header, so the server will know to unzip the content and pass it correctly to the controller
I can gzip the content on my side, and re-open it manually on the server, but I thought there should be some way to do it automatically. Is there?
See this post, like that you could give a parameter on the model so the server can decide if the content is a file and if the file should be unziped first
function Ctrl($scope, $http) {
//a simple model to bind to and send to the server
$scope.model = {
gzip: true,
file: true
};
//an array of files selected
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});
//the save method
$scope.save = function() {
$http({
method: 'POST',
url: "/Api/PostStuff",
//IMPORTANT!!! You might think this should be set to 'multipart/form-data'
// but this is not true because when we are sending up files the request
// needs to include a 'boundary' parameter which identifies the boundary
// name between parts in this multi-part request and setting the Content-type
// manually will not set this boundary parameter. For whatever reason,
// setting the Content-type to 'false' will force the request to automatically
// populate the headers properly including the boundary parameter.
headers: { 'Content-Type': false },
//This method will allow us to change how the data is sent up to the server
// for which we'll need to encapsulate the model data in 'FormData'
transformRequest: function (data) {
var formData = new FormData();
//need to convert our json object to a string version of json otherwise
// the browser will do a 'toString()' on the object which will result
// in the value '[Object object]' on the server.
formData.append("model", angular.toJson(data.model));
//now add all of the assigned files
for (var i = 0; i < data.files; i++) {
//add each file to the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
//Create an object that contains the model and files which will be transformed
// in the above transformRequest method
data: { model: $scope.model, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
};
};
Related
I have a code
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
I know this code is change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded". But i dont know what is syntax of it . What is obj in function . Please explain for me . Thank
Transform Request is generally used for converting request data in the format which can be easily handled by server (Your Back end code).
For Example - If you want to send data with some modification in request then you can use it .
$scope.save = function() {
$http({
method: 'POST',
url: "/Api/PostStuff",
//IMPORTANT!!! You might think this should be set to 'multipart/form-data'
// but this is not true because when we are sending up files the request
// needs to include a 'boundary' parameter which identifies the boundary
// name between parts in this multi-part request and setting the Content-type
// manually will not set this boundary parameter. For whatever reason,
// setting the Content-type to 'undefined' will force the request to automatically
// populate the headers properly including the boundary parameter.
headers: { 'Content-Type': undefined},
//This method will allow us to change how the data is sent up to the server
// for which we'll need to encapsulate the model data in 'FormData'
transformRequest: function (data) {
var formData = new FormData();
//need to convert our json object to a string version of json otherwise
// the browser will do a 'toString()' on the object which will result
// in the value '[Object object]' on the server.
formData.append("model", angular.toJson(data.model));
//now add all of the assigned files
for (var i = 0; i < data.files; i++) {
//add each file to the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
//Create an object that contains the model and files which will be transformed
// in the above transformRequest method
data: { model: $scope.model, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
};
};
Downloading a file used to work fine in my application until I upgraded Angular to the latest. Even now, the file is getting downloaded, but the issue is that it is getting corrupted. Upload file is working fine and if we check in the file server, the file will be intact. But upon download, I am getting corrupted file.
Html :
<td data-title="''">
<a tooltip="Download CV" ng-hide="!talent.resumePath" tooltip-trigger tooltip-animation="false" tooltip-placement="bottom" ng-click="downloadResume(talent.id)" data-placement="top" data-toggle="tooltip" data-original-title="resume">
<img src="../../img/DownloadIcon.png" /></a>
</td>
Controller :
downloadResume: function(employeeId) {
return apiServices.getFileFromTalentPool('/talentpool/resume?id=' + employeeId)
},
Where, getFileFromTalentPool is : https://hastebin.com/yivaterozi.js
Endpoint :
public FileResult GetResume(int id) {
var result = _services.GetResume(id);
if (result != null) {
HttpContext.Response.ContentType = result.ContentType;
HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "FileName";
HttpContext.Response.Headers["FileName"] = result.FileDownloadName;
}
return result;
}
Usually I download Doc files. I tried with a notepad file to see if it's the same. Strangely, I noticed that I am able to open the notepad file, but its content is manipulated to something like [object Object]. But for Doc files, it just shows:
How can I fix this?
it looks like the code at https://hastebin.com/yivaterozi.js was updated from using deprecated $http.success() method to current $http.then(). Promise' success callback function (within then method) receives only one object argument: https://docs.angularjs.org/api/ng/service/$http. Deprecated 'success' method got more arguments (data, status, headers) and data already contained raw data. When using then(), data is located under data property of response, so try to change your $http call to:
$http({
method: 'GET',
cache: false,
url: fileurl,
responseType:'arraybuffer',
headers: {
'Authorization': "Bearer " + $rootScope.userInfo.access_token,
'Access-Control-Allow-Origin': '*'
}
}).then(function (data) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get the headers
var headers = data.headers();
...
...
please note that headers are fetched correct here from the data object and not from the third argument (just add var, since we removed empty arguments).
Now in each place that you use data, change it to data.data, like:
// Try using msSaveBlob if supported
var blob = new Blob([data.data], { type: contentType });
or just change argument data to response and add var data = response.data; anf modify headers getter to headers = response.headers();:
$http({
method: 'GET',
cache: false,
url: fileurl,
responseType:'arraybuffer',
headers: {
'Authorization': "Bearer " + $rootScope.userInfo.access_token,
'Access-Control-Allow-Origin': '*'
}
}).then(function (response) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get data
var data = response.data;
// Get the headers
var headers = response.headers();
...
...
I'm trying to learn ExpressJS and I'm having trouble getting IP address from an Express route to display in the browser via Angular controller.
I'm using 2 Nodejs modules (request-ip and geoip2) to get the IP and then lookup geolocation data for that IP. Then trying to use Angular to display the geolocation data in the browser using an Angular $http get call.
My Express route for the IP:
// get IP address
router.get('/ip', function (req, res, next) {
console.log('requestIP is ' + ip);
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
//return res.status(400).json({error: 'Something happened'});//default
return res.sendStatus(400).json({error: 'Something happened'});
}
else if (result) {
return res.send(result);
}
});
});
And my AngularJS controller code:
function MainController($http) {
var vm = this;
vm.message = 'Hello World';
vm.location = '';
vm.getLocation = function() {
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
};
};
The Hello World message displays but not the location...? I can also go to localhost:8000/ip and see the JSON result. The result doesn't appear in Chrome's console either. The result is a json object like this:
{"country":"US","continent":"NA","postal":"98296","city":"Snohomish","location":{"accuracy_radius":20,"latitude":47.8519,"longitude":-122.0921,"metro_code":819,"time_zone":"America/Los_Angeles"},"subdivision":"WA"}
I'm not sure why the Hello Word displays and the location doesn't when it seems that I have everything configured correctly... so obviously I'm doing something wrong that I don't see...?
You have initialised 'vm.location' as a string when in fact it is a JSON object.
vm.location = {};
You need to adjust the url paramater in your request to:
url: '/ip'
As you are sending back JSON from Express.js, you should change your response line to:
return res.json(result);
Do you call vm.getLocation() somewhere in your code after this?
The data you need is under result.data from the response object.
Also in order to display the data in the html you have to specify which property to display from the vm.location object (vm.location.country, vm.location.city etc..).
From angular docs about $http:
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Is this express js and angular hosted on the same port? If so please replace your
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
with
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
It may be considered as CORS call and you have it probably disabled.
You can also specify second function to then (look code below) and see if error callback is called.
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
}, function (error) {
console.log(error);
});
I encountered a bug in a square-connect API wrapper for node, and I made a fiddle to recreate the issue. I noticed my code wasn't working, in the sense that angular {{}} stuff isn't showing up. What's wrong with it?
the only thing I'm trying to do is have the raw JSON object (preferably {{res}}, but it doesn't matter really) shown below the create button. I am just trying to demonstrate to the author of a library that my object and data is valid, and that a bug is in his library, not my implementation.
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: item
}).success(function(data, status) {
$scope.res = data;
}).failure(function(data, status){
$scope.res = data+status;
});
data is not being returned from jsfiddle's ECHO.
http://jsfiddle.net/efjytg6r/2/
You were close, but since you're saving your $http in a variable, you access the methods within it using that variable. (ie: httpRequest.success / etc)
Also it's .error() not .failure()
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: item
});
httpRequest.success(function(data, status) {
$scope.res = data;
});
httpRequest.error(function(data, status){
$scope.res = data+status;
});
jsFiddle is finicy with it's echo AJAX examples. You need to format what you send to them correctly with json, have it stringified as well as use jQuery's $.param (since angular doesn't do POST like you're used to with jQuery).
I included jQuery to the fiddle below.
I formatted the data being sent differently
I moved your {{ res }} inside of the controller area (you had it outside, which means it won't compute)
I added | json filter to {{ res | json }}
Updated jsFiddle
// the wacky format you need if you want to do fake $http to jsFiddle
// case in point, if you're trying to DEMO this, I wouldn't even bother, since it won't look like this when you actually use this within your application
var data = $.param({
json: JSON.stringify({
item
})
});
$http.post("/echo/json/", data)
.success(function(data, status) {
$scope.res = data;
}).error(function (status) {
});
Here is an example using $httpParamSerializer and a delay.
angular.module('myApp',[]);
angular.module('myApp').controller('myVm',
function($scope,$http,$httpParamSerializer) {
var vm = $scope;
var xitem = {a:"1",b:"2"};
var data = $httpParamSerializer({
json: xitem,
delay: 6
});
console.log("Posting xitem");
vm.p = $http.post('/echo/json/',data);
vm.p.then (function(response) {
console.log(response);
console.log(response.data)
})
});
I am trying to use restangular for file upload post request , I want to achieve the same functionality as below in restangular.
However, I was unsure how to set content type and transformRequest for just this particular request. If I understand correctly, setDefaultHeader sets it for all subsequent requests. Is there some other way?
myApp.service('$fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var filedata = new FormData();
filedata.append('file', file);
$http.post(uploadUrl, filedata, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
You have 2 situations here, the POST for create a new item or the PUT to edit an item:
// Save new Item
$scope.saveNew = function (item) {
var data = new FormData();
angular.forEach(item, function (fieldData, field) {
data.append(field, fieldData);
});
Restangular
.all('items')
.withHttpConfig({transformRequest: angular.identity})
.post(data, {}, {'Content-Type': undefined})
.then(function () {
// do on success
}, function () {
// do on failure
});
};
// Edit existing Item
$scope.save = function (item) {
var data = new FormData();
angular.forEach(item.plain(), function (fieldData, field) {
data.append(field, fieldData);
});
Restangular
.one('items', item._id)
.withHttpConfig({transformRequest: angular.identity})
.customPUT(data, undefined, {}, {'Content-Type': undefined})
.then(function () {
$location.path('sites');
});
To set the headers for a single request all you'll need to do is add an object containing the name and value of the headers as an argument to .post(), .get() or whatever method you need.
https://github.com/mgonto/restangular#element-methods
Restangular.all('some-endpoint').post(postContent, {}, {'Content-Type': undefined}).then(function (response) {
console.log('Weeeeee!!!');
});
As for the transformRequest I am unsure of, I haven't had to deal with anything like that before, this is the only thing I could find on it in the documentation:
https://github.com/mgonto/restangular#setdefaulthttpfields
But that seems to set it for all the request which isn't what you want, but it's something at least.
Anyway, hopefully this will help you get what you want.
Edit:
Since most of the request types in restangular have a query param and then the headers you need to pass in a blank query param object and then the headers, example has been updated to show this.
Since this is the first hit on Google for this issue, see Issue 420 in the Restangular issue tracker.
Basically the newest Restangular has a withHttpConfig function to set $http options right before a request is dispatched.
If you have a route at a URL something like example.com/api/users/:id/picture that accepts a multipart upload with an image for a specific user you could do something like:
Users.one(2)
.withHttpConfig({transformRequest: angular.identity})
.customPOST(filedata, 'picture', undefined, {'Content-Type': undefined})
.then(function(resp) {
// File data post is complete here
});
By default Angular will transform any data sent with $http to JSON. The transformRequest configuration simply replaces that default transformation with a NOP.