Post array of objects with AngularJS $http - json

I am making an app where a user can submit multiple links to a form. The links are then stored in an array of objects before posting them to my backend. But somehow my JSON structure turns up like this in ExpressJS:
[
'{"title":"link1","url":"url1"}',
'{"title":"link2","url":"url2"}'
]
This is my angularJS:
$scope.saved_link = [];
$scope.uploadLink = function(title,url) {
$scope.saved_link.push({
title : title,
url : url
});
}
$scope.onSubmit = function(pubForm, url) {
var file = $scope.upload_file;
var fd = new FormData();
fd.append('file', file);
$http.post(url,fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
params: {
links: $scope.saved_link,
image: file.name
}
}).then(function successCallBack(response){
})
}
Any one know how to get rid of those quotation marks?

I believe the Content-Type must be set for fixing the format.
Content-Type: application/json
Ref:
AngularJS $http
Alternatively,
you can try to parse the string into an object at the backend.
Ref:
JSON.parse()

Related

send post from webpage to Node.js server ...do not use 'fetch'...?

I am using the following javascript on a webpage to send information to a Node.js server upon a "click" on an image. This is using a 'POST' request.
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
var response = fetch("members/pages/:" + splits[1] + "/presence/:" + available, {
method: 'POST',
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
});
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
And here I handle the request in my Node.js server code:
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/members/pages/:membername/presence/:online', urlencodedParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.params)
console.log(req.body)
res.redirect('/_landing');
})
Here is my console output:
I RECEIVED FROM CLIENT THE FOLLOWING:
{ membername: ':Nica', online: ':Yes' }
{}
As can be seen from my output, the POST route does seem to be functional, somewhat. However my 'redirect' command does NOT execute...the webpage does not change to the '_landing' page as it should...I think it may be because I am using 'fetch' to send the POST request...??? Can somebody verify if that is the cause (or another issue is the cause) and how I might be able to correct the issue?
In addition why does my 'params' include the colons (":") when I log to the console...is that standard? I would not think it would include the colons in the log, only the actual data.
Basically it seems my POST is almost working...but not exactly. Any suggestions would be greatly appreciated. I thank you in advance.
UPDATE: I have made some changes and my POST seems to be working fine now. In my frontend webpage I use the following to make the HTTP POST request:
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
fetch('/members/pages/callup', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({name: splits[1], presence: available, str: 'Some string: &=&'})
})
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
...And modified my route handler in my Node.js script:
// create application/json parser
var jsonParser = bodyParser.json()
app.post('/members/pages/callup', jsonParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.body)
res.redirect('/_landing');
})
This is functional...to receive the data sent from the frontend webpage.
The only remaining problem is why does the 'redirect' not fire...??? I still have a feeling that by using a 'fetch' that somehow this is interfering with the page redirection...? A fetch would normally be used to wait for a response from the server, in my case I am not interested in that functionality I just want to send data one-way from frontend to backend...and then redirect the frontend page. I cannot think of any other reason why the redirect does not fire...?
Make extented:true instead of false as,
var urlencodedParser = bodyParser.urlencoded({ extended: true }) and move this line above of the below statement,
var jsonParser = bodyParser.json() and check if it works.
And finally change your headers here from,
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
To,
headers: {
'Content-Type': 'application/json'
}
Hope this will resolve the issue.

CouchDb 2.1.1 Admin API Compaction PUT Request

I am working in NodeJS with CouchDB 2.1.1.
I'm using the http.request() method to set various config settings using the CouchDB API.
Here's their API reference, yes, I've read it:
Configuration API
Here's an example of a working request to set the logging level:
const http = require('http');
var configOptions = {
host: 'localhost',
path: '/_node/couchdb#localhost/_config/',
port:5984,
header: {
'Content-Type': 'application/json'
}
};
function setLogLevel(){
configOptions.path = configOptions.path+'log/level';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldLogLevel: " + responseString);
});
});
var data = '\"critical\"';
req.write(data);
req.end();
}
setLogLevel();
I had to escape all the quotes and such, which was expected.
Now I'm trying to get CouchDb to accept a setting for compaction.
The problem is that I'm attempting to replicate this same request to a different setting but that setting doesn't have a simple structure, though it appears to be "just a String" as well.
The CouchDB API is yelling at me about invalid JSON formats and I've tried a boatload of escape sequences and attempts to parse the JSON in various ways to get it to behave the way I think it should.
I can use Chrome's Advanced Rest Client to send this payload, and it is successful:
Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb#localhost/_config/compactions/_default
Request Body: "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"
This returns a "200 OK"
When I execute the following function in my node app, I get a response of:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
function setCompaction(){
configOptions.path = configOptions.path+'compactions/_default';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldCompaction: " + responseString);
});
});
var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";
req.write(data);
req.end();
}
Can someone point at what I'm missing here?
Thanks in advance.
You need to use node's JSON module to prepare the data for transport:
var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';
// Show the formatted data for the requests' payload.
JSON.stringify(data);
> '"[{db_fragmentation, \\"70%\\"}, {view_fragmentation, \\"60%\\"}, {from, \\"23:
00\\"}, {to, \\"04:00\\"}]"'
// Format data for the payload.
req.write(JSON.stringify(data));

Http post request in Angular2 does not pass parameters

I am trying to send a parameter using Angular2 POST to my Python/Tornado back-end which returns a JSON object. The parameters are being sent properly but at the Python side, it is returning 400 POST missing arguments error. I am using Ionic 2/Angular2 in the front-end and Python/Tornado server.
Angular2 code is as follows:
Here content is a variable containing HTML table
let body = JSON.stringify({content: content});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map(res => res.json()).subscribe(data => {
console.log(data)
}, error => {
console.log(JSON.stringify(error));
});
Python code is as follows:
def post(self):
print self.request.arguments
print self.get_argument('content')
self.finish(dict(result="ok", data=content))
Here is the error:
[W 160824 06:04:30 web:1493] 400 POST /test (182.69.5.99): Missing argument content
[W 160824 06:04:30 web:1908] 400 POST /test (182.69.5.99) 1.67ms
Your Angular2 code looks reasonable, however your Python code is wrong, because you are treating the request as x-www-form-urlencoded. You have to access the JSON string through the request.body property:
data = tornado.escape.json_decode(self.request.body)
See https://stackoverflow.com/a/28140966/2380400 for an answer to a similar question.
You should maybe try to use something like URLSearchParams() with an URLencoded content type. I don't know much about Tornado but I am using ASP controllers and it works fine.
See Angular2 Documentation : https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html
Watch the following authentication example I am using :
controllerURL: string = "/APIConnexion";
login(aLogin: string, aMdp: string) {
// parameters definition (has to have the same name on the controller)
let params = new URLSearchParams();
params.set("aLogin", aLogin);
params.set("aMdp", aMdp);
// setup http request
let lHttpRequestBody = params.toString();
let lControllerAction: string = "/connexion";
let lControllerFullURL: string = this.controllerURL + lControllerAction;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
// call http
return this.http.post(lControllerFullURL, lHttpRequestBody, options)
.map((res: any) => {
// data received as JSON
let data = res.json();
// Do something with your data
}
).catch(this.handleError);
}

how to post json object in apigee baas using titanium studio

var jsonobj = { "username" : "cat" };
var client=Ti.Ui.createHttpClient({
onload:{ },
onerror : { }
});
client.open('POST',api.usergrid.com/serv-d/demo1/logs);
client.send(jsonobj);
Details:
jsonobj is the json object to be posted in the apigee baas.
client.open has the url for the apigee baas.
client.send sends the json object.
You need to send your data as JSON payload not as url encoded POST fields as it is being sent right now. You just need to set the content-type to json.
var client = Ti.Ui.createHttpClient({
onload:{ },
onerror : { }
});
client.setRequestHeader('content-type', 'JSON');
client.open('POST',api.usergrid.com/serv-d/demo1/logs);
client.send(JSON.stringify(jsonobj));
I think your jsonobj should be:
var jsonobj = {username: uname, password: pass};
Since JSON.stringify() will take care of stringify-ing it.
Let's do some testing with:
var client = Ti.Network.createHTTPClient();
client.open('POST', 'http://requestb.in/1b1yblv1');
client.send(payload);
With:
var payload = {username: "cat"};
At http://requestb.in/1b1yblv1?inspect you see:
username=cat
With:
var payload = JSON.stringify({username: "cat"});
It is:
{"username":"cat"}
So that's what you need right?

HTML5 localStorage and Dojo

I am working in DOJO and my task is i have one JSON file and the datas are coming from JSON url. So now i have to read JSON url and save the datas to browser using HTML5 localStorage, after saving i have to read datas from browser and i have to display in DOJO. Guys any one know about this kindly help me..
Function for getting json data
function accessDomain(dom_sclapi, handle) {
var apiResponse;
//accessSameDomain
if(!handle) {
handle = "json";
}
dojo.xhrGet({
url : dom_sclapi,
handleAs: handle,
sync: true,
headers: { "Accept": "application/json" },
//Success
load: function(Response) {
apiResponse = Response;
},
// Ooops! Error!
error: function(Error, ioArgs) {
//apiResponse = Error;
//console.log(ioArgs.xhr.status);
}
});
//apiResponse
return apiResponse;
}
where dom_sclapi = <json url>
Call
var data = accessDomain(<jsonurl>,'json');
then
console.log(data);
You can see the json o/p in console window. Now you can dispaly to html page using,
dojo.forEach(data, function(eachData){
//script for each json element eg: eachData.displayName;
});