How to send POST request with multipart/form-data using angularJS? - angularjs

I've asked something like that before, but here are slightly different cases and more details.
I have a handler on the server side which is accepting multipart/form-data POST requests. Request contains number of POST parameters and one more parameter which should contain image file (this last parameter may exist or may not exist). How to send such requests using angularJS?
I've tried number of options (all of them for know without file uploading) but none of them works. I'm getting wrong result because absence of Content-Type: multipart/form-data in the HTTP request, or getting exception from Jetty-based Spark web-services tool (pleas don't confuse with Apache Spark) which sounds like "..."Missing initial multi part boundary..." - depending on the request details.
I've tried this:
return $http({
method: 'POST',
url: editCompanyUrl,
headers: {'Content-Type': 'multipart/form-data'},
data: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and this for example
return $http({
method: 'POST',
url: editCompanyUrl,
headers: {'Content-Type': undefined},
data: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
Could you please help? What is the right way to send multipart requests?
Thank you.
Kind regards, Artem.

$http provides an option : params.
Use params: instead of data:
$http({
url: url,
method: "POST",
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
}).success(function(data, status, headers, config) {
//SUCCESS
}).
error(function(data, status, headers, config) {
//ERROR
});

Can you show us the complete error. And also your server side code. To get multi part content in Spark, you have to use this at your server side:
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("Yourstoragedirectory");
request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
System.out.println(request.raw().getPart("file"));
Also make sure you have the latest version of spark.

Related

Angular $http post call passing data issue to GO backend

I am trying to get access to backend written in GO which in 99% is good (problem does not lay there).
For now I just created simplest call which stay in controller (it will be in service in future) to register new user. Although I hardcoded data which I am passing the response says 403 forbidden. In powerShell shows reason of 403:
RegistrationForm parse - email: , nick:
Validation failed for email - blank
It looks like I am not passing my data correctly because email is blank. Please take a look at my code:
$ctrl.fake_registerSubmit = function() {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
data: {
email: 'check#onet.pl',
nick: 'borysxoxo',
password: 'admin12312',
password_confirmation: 'admin12312'
}
})
.then(function successCall(response, post) {
console.log('user added');
}, function errorCall(respone) {
console.log('error callback');
console.log(respone);
})
};
This screenshot presents API documentation which I am trying to access:
link
What am I doing wrong? Is there other way to pass data?
You are sending some json data with the wrong Content-Type.
I see 2 options, either change Content-Type in your header to:
'Content-type' : 'application/json'
or transform your payload to:
data: "email=check#onet.pl&nick=borysxoxo&password=admin12312&password_confirmation=admin12312"

Set one of the angular HTTP data variables to a boolean

Edit: Is this possibly an issue with the backend API? The data requests sent over $.param are always strings, correct? So they need to parse that stuff on their backend?
I am currently trying to send a post request to an API to register a user. One of the requirements is to accept terms and conditions and an age requirement, which it expects a boolean.
I believe the issue might be that the $http request is sending a STRING and not a boolean to the API backend and so it's rejecting it. How would I send a boolean through $http?
var apiCall = {
method: 'POST',
url: 'API_URL',
data: $.param({
'user[email]': username,
'user[password]': password,
'user[password_confirmation]':password,
'profile[age_acceptance]': ageAcceptance,
'profile[terms_acceptance]': termsAcceptance
}),
headers: {
'Accept': 'application/vnd.softswiss.v1+json',
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(data, headersGetter, status) {
console.log(data);
console.log(headersGetter(data));
}
}
var dataToPost = JSON.stringify( {
'user[email]': username,
'user[password]': password,
'user[password_confirmation]':password,
'profile[age_acceptance]': ageAcceptance,
'profile[terms_acceptance]': termsAcceptance
});
data: dataToPost,
headers: {.......,
.....
you have to stringy your parameters.
JSON.stringify(params)

AngularJS HTTP GET request returning cached data

In my AngularJS app I am sending HTTP GET request as below.
MyService.HttpReq("testUrl", "GET", null);
HttpReq Method is defined in a service and implemented as below:
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: postData,
headers: {
'Content-Type': 'application/json',
}
}).success(function(response)
{
console.log("Success: "+JSON.stringify(response));
}).error(function(data, status)
{
console.error("Error");
});
}
First of all is this the right way of sending HTTP request in AngularJS?
The problem that I am facing is, some times I get cached data as response and HTTP request is not hitting the server. what can be the issue?
UPDATE
As per the comment and answer I have updated my HTTP request code as below, but still getting same issue.
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: payload,
headers: {
'Content-Type': 'application/json',
'Cache-Control' : 'no-cache'
}
}).
then(
function(response)
{
var data = response.data;
console.log("Success: "+JSON.stringify(data));
},
function(response)
{
var data = response.data || "Request failed";
var status = response.status;
console.error("Error: "+JSON.stringify(data));
}
);
}
IE Browsers will catch ajax get requests even if we add cache control headers to the response. Only way i found to solve the issue is to add some random parameter to the request. Please make sure the api have no problem even if you send extra parameters
MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
Just add cache: false attribute to config object.
https://docs.angularjs.org/api/ng/service/$http#caching
Also you can add header: 'Cache-Control' : 'no-cache'

Adding content-type header to Angular $http request

I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.

Paypal API with angular and cURL

Currently I'm working with paypal API and flowing with this document make your first call.
When I sent a request through angular $http to paypal, I got a Status Code 415. It's seems like I missed something, does anyone can help me? :)
here is my code
$http({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
headers: {'Content-Type': 'application/json',
'auth-token': 'EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp',
'Accept-Language': 'en_US'
},
data: { 'grant_type': 'client_credentials' }
}).success(function (data, status, headers, config) {
console.log(data)
}).error(function (data, status, headers, config) {
console.log(data)
});
Referring to the Paypal doc
Tip: If you're using Windows, we recommend you make cURL calls using a
Bash shell. If you're not using cURL calls, set the content-type to
application/x-www-form-urlencoded for this request.
Try set the content_type as application/x-www-form-urlencoded

Resources