Set one of the angular HTTP data variables to a boolean - angularjs

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)

Related

Sending POST request weird issue

I'm quite new with ANGULAR and web development in general and I'm currently working on a web tool. Now I want this tool to send a POST request to a web service but Im encountering a weird bug. Now I have below code in my javascript:
var data_info = { test_id: 'TEST', model_id: 'TEST:TEST_ID' };
//data_info = JSON.stringify(data_info);
var request_json = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: data_info,
cache: false,
};
console.log(request_json);
$http(request_json).then(function successCallback(response) {
// response code here
}
Now this code currently doesn't pass the preflight request check and is always returning a 405. But if I change the line data: data_info in the request JSON into a new key let's say body: data_info it now successfully sends the request and I can confirm that the service is receiving it. I'm not sure what's the issue here and can't figure it out.
change your header to :
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
Please try

Http request in angular send undefine values

** It turns out that the problem was at the server **
I'm trying to excute HTTP post request (from my angular client) to my server (node express). The server recive the request but the data is undefined.
Already tried to make this req by postman and it worked perfect there.
var req = {
method: 'POST',
url: _url +'/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { user: 'someUser', password :'somePass' }
}
$http(req)
.then(function success(res){
...
}, function error(res){
...
});
You are sending JSON data and sending the header of x-www-form-urlencoded.
Change the content type to "application/json"
Like:
headers: {
'Content-Type': 'application/json'
}

Nodejs sending external API POST request

i am trying to send a POST request from my angularjs controller to the nodejs server which should then send a full POST request to the external API and this way avoid CORS request as well as make it more secure as i'm sending relatively private data in this POST request.
My angularjs controller function for making the post request to the nodejs server looks like this and it works fine:
var noteData = {
"id":accountNumber,
"notes":[
{
"lId":707414,
"oId":1369944,
"nId":4154191,
"price":23.84
}
]
}
var req = {
method: 'POST',
url: '/note',
data: noteData
}
$http(req).then(function(data){
console.log(data);
});
Now the problem lies in my nodejs server where i just can't seem to figure out how to properly send a POST request with custom headers and pass a JSON data variable..
i've trierd using the nodejs https function since the url i need to access is an https one and not http ,i've also tried the request function with no luck.
I know that the url and data i'm sending is correct since when i plug them into Postman it returns what i expect it to return.
Here are my different attempts on nodejs server:
The data from angularjs request is parsed and retrieved correctly using body-parser
Attempt Using Request:
app.post('/buyNote', function (req, res) {
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
},
data = JSON.stringify(req.body);
};
request(options, function (error, response, body) {
if (!error) {
// Print out the response body
// console.log(body)
console.log(response.statusCode);
res.sendStatus(200);
} else {
console.log(error);
}
})
This returns status code 500 for some reason, it's sending the data wrongly and hence why the server error...
Using https
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
}
};
var data = JSON.stringify(req.body);
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.write(data);
req.end();
Https attempt return a 301 status for some reasons...
Using the same data, headers and the url in Postman returns a successful response 200 with the data i need...
I don't understand how i can make a simple http request...
Please note: this is my first project working with nodejs and angular, i would know how to implement something like this in php or java easily, but this is boggling me..
So after a lot of messing around and trying different things i have finally found the solution that performs well and does exactly what i need without over complicating things:
Using the module called request-promise is what did the trick. Here's the code that i used for it:
const request = require('request-promise');
const options = {
method: 'POST',
uri: 'https://requestedAPIsource.com/api',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json',
'Authorization': 'bwejjr33333333333'
}
}
request(options).then(function (response){
res.status(200).json(response);
})
.catch(function (err) {
console.log(err);
})

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'

How to send POST request with multipart/form-data using 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.

Resources