Trying to run a postman (pm) api call to run a request from the test tab.
Getting back streams in response (logged in console as array containing integers).
Any idea as to how to read these streams.
Request:
pm.sendRequest({
url: myUrl,
method: 'GET',
header: {
'content-type': 'application/json'
}
}, function (err, res) {
console.log(res)
});
Response:
Object:{}
code:200
cookie:[]
header:[]
0:{}
1:{}
2:{}
3:{}
4:{}
5:{}
6:{}
id:"e5d5d6d6"
responseSize:55551
responseTime:263
status:"OK"
stream:{}
data:[]
0:123
1:10
2:32
3:32
4:34
5:115
6:119
7:97
8:103
9:103
10:101
11:114
12:34
13:32
14:58
15:32
16:34
17:50
18:46
19:48
20:34
21:44
22:10
23:32
24:32
25:34
Just use:
res.json()
This gives the response body in json format.
Usage:
pm.sendRequest('url', (err, res) => {console.log(res.json());}
You need to use toJSON() function on the Response object to serialize it to a human-readable format:
function (err, res) {
console.log(res.toJSON())
});
See the pm Sandbox API for further reference.
If response of below request is in XML format,
pm.sendRequest({
url: myUrl,
method: 'GET',
header: {
'content-type': 'application/json'
}
}, function (err, res) {
console.log(res)
});
I am trying to convert response using below code
var jsonObject = xml2Json(res);
It is giving error saying
JSONError | Unexpected token u in JSON at position 0
When I used that same function with testscript, It is converting XML to hsonObject
var jsonObject = xml2Json(responseBody);
This answer didn't work for me as my reply was a HTML page with embedded JS. I had to use pm.response.text() and painstakingly parse out the code I wanted by using .spit('\n') to get an array of lines, etc.
Related
So I currently have the functioning code in python
import requests
import json
address = "*address here*"
viewkey = "*viewkey here*"
headers = {'content-type': 'application/json'}
url = "https://api.mymonero.com:8443/get_address_txs"
data = {"address":address,"view_key":viewkey}
data = json.dumps(data)
response = requests.post(url, data=data, headers=headers)
print(response.text)
And I tried to move to nodejs to integrate it with another program I have written
var request = require('request');
var options = {
url: 'https://api.mymonero.com:8443/get_address_txs',
headers: {'content-type': 'application/json'},
data: JSON.stringify({
address:"address",
viewkey:"viewkey"
})
};
request.post(options,function(error, response, body) {
console.log(body);
})
I assumed the code would be identical but clearly not I get an error from the server with the second segment of code. Please could someone help me migrate this?
Note: I know requests in python has a json attribute I have written it in python this way for clarity.
For the record the response I get from the javascript is:
{
"Error": "Problems parsing JSON"
}
When I get from python:
{
"total_received": "152840132538",
"scanned_height": 2589644,
"scanned_block_height": 1320308,
"start_height": 2586111,
...
}
Do not stringify your msg. That should be it.
In your json, in python the key is view_key, in javascript it's view key.
Also, the request library doesn't have a data key in it's options. You can use body to set the raw body. If you use json, the body will be the son representation of the dict you pass, and the Content-Type header is set for you .
Right I'm an accidental genius I have no idea why my current method wasn't working but the solution I came up with was:
var request = require('request');
var options = {
url: 'https://api.mymonero.com:8443/get_address_txs',
headers: {'content-type': 'application/json'},
json: {
"address":"*address*",
"view_key":"*viewkey*"
}
};
request.post(options,function(error, response, body) {
console.log(body);
})
No idea why it works but hey that's life thank you so much for your suggestions.
My program sends some JSON to my API (which works fine):
var result = await fetch('http://localhost:58553/api/Foo', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)
});
var contentResult = await result.text();
var contentResultObject = JSON.parse(contentResult);
console.log(contentResult);
console.log(contentResultObject);
console.log(contentResultObject.code);
The output of console.log:
"{\"code\":1,\"probability\":0.985368549823761}"
{"code":1,"probability":0.985368549823761}
undefined
Any reason why this isn't working? My API simply returns a string:
return JsonConvert.SerializeObject(result);
Your output of contentResult looks like your payload has been double encoded. You can verify this by logging typeof contentResultObject, which should show string.
To fix the problem you will ideally address the double encoding issue on the server, but if you can't you can simply apply JSON.parse twice.
I wrote the below code to send the $http.post request
$http({
url: '/OA_HTML/ReportColumnSelection.jsp',
method: 'POST',
data: JSON.stringify({myData : $scope.reportColumns}),
headers: {'Content-Type': 'application/json;charset=utf-8'}
})
.success(function(response){
$scope.viewColumns = response.columnData;
})
.error(function(response){
//Error Log
console.log('Inside saveReportColumns Error');
});
Now the problem is i'm unable to get the "myData" JSON in ReportColumnSelection.jsp
request.getParameter("myData");
Please let me know if i'm doing anything wrong.
AngularJS Version 1.4.7
Code to save report columns:
$scope.saveReportColumns = function () {
console.log('Inside saveReportColumns');
$http({ url: '/OA_HTML/eis/jsp/reporting/reports/newreport/columnselection/EISRSCReportColumn‌​SelectionAM.jsp',
method: 'POST',
data: JSON.stringify({myData:$scope.reportColumns}),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).success(function(response){}).error(function(response){
//Error Log console.log('Inside saveReportColumns Error');
});
};
The $http services default content type is application/json, which your JSP cannot parse.
You can either,
change the content type of the request to application/x-www-form-urlencoded;charset=utf-8 (which might have other implications)
or
read it as a stream like below.
InputStream body = request.getInputStream();
It might be a good idea to leave the content type as it is, and instead read the request body and parse it with a library such as google/json
BufferedReader reader = request.getReader();
Gson gson = new Gson();
I am trying to pass JSON string in ajax request. This is my code.
NewOrder = JSON.stringify (NewOrder);
alert (NewOrder);
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: "mydata="+ NewOrder
};
$http(req)
.success(function (data, status, headers, config) {
alert ('success');
})
.error(function (data, status, headers, config) {
alert (status);
alert (data);
alert ('Error')
});
alert (NewOrder) gives -
{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}
Which seems to be a valid JSON string.
But in script side I am getting following error. in this line
my $decdata = decode_json($cgi->param('mydata'));
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")
Can please someone help me why i am getting this error?
$cgi->param('myData') returns the query param string 'mydata', which in your case is not sent.
You're posting the json data in the request body of your http post payload, and not as a query/form param. In that case, you'd need some other function to read the contents of the request body in your server-side script.
which happens to be:
my $data = $query->param('POSTDATA');
as described in here: http://search.cpan.org/~lds/CGI.pm-3.43/CGI.pm#HANDLING_NON-URLENCODED_ARGUMENTS
Also you should remove the "mydata=" from your json in the body you post, because http request payload bodies do not have parameter names (they're for query/form-params only).
Your end code should be like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: NewOrder
};
and the servers side:
my $decdata = decode_json($query->param('POSTDATA'));
I think it may be related to this issue: AngularJs $http.post() does not send data
Usually I would post data like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: {"mydata" : NewOrder}
};
However I am assuming that you are expecting the data as request params from this:
my $decdata = decode_json($cgi->param('mydata'));
If that is the case then the linked SO question is what you are looking for.
Angular $http.post accepts two params as url and payload
var url = '/cgi-bin/PlaceOrder.pl';
var payLoad = {'myData' :JSON.stringify(NewOrder)};
$http.post(url, payLoad)
.success(function(data) {
console.log(success);
})
At the server side, while fetching the required json string from the request param and then desearlize the json as following:
$result = $cgi->param('myData');
my $decdata = decode_json($result);
I'm trying to do:
$.ajax({
type:"POST",
url:"/psychos",
data:JSON.stringify(this.psycho)
})
At server I got:
app.post("/psychos", function(request, response) {
var psychologist = request.body.psycho
console.log(psychologist)
psicologosCollection.insert(psychologist, function(error, responseFromDB) {
if (error) {response.send(responseFromDB)}
console.log("Se ha insertado: "+ JSON.strinfigy(responseFromDB))
response.send(responseFromDB)
})
})
But, the console.log() is printing undefined and got the following throw:
TypeError: Cannot read property '_id' of undefined
at insertWithWriteCommands (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:78:13)
at Collection.insert (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:30:7)
at Object.handle (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/server.js:117:25)
at next_layer (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:107:5)
at c (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:195:24)
at Function.proto.process_params (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:251:12)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:189:19)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:166:38)
at Layer.session [as handle] (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express-session/index.js:98:29)
I'm using BodyParser before:
var bodyParser = require('body-parser')
app.use(bodyParser())
psycho is actually a valid existing object. At the method where AJAX is performed a console.log(this.psycho) will print my object. What am I doing wrong?
Edit:
Even I found out I should have got:
var psychologist = request.body.psycho
at server GET route code, I can't understand how bodyParser generates an Object?
For a quite similar AJAX call I tried before:
function getSendingJSON(url,reqObject,callBack) {
$.ajax({
type: "get",
data: reqObject,
dataType: "json",
url: url,
success: function(response){
callBack(response);
}
});
}
So response was a JSON, and callback function looked similar to:
function plotReglaFalsa(respuesta) {
if (respuesta.fail) {...}
else if (respuesta.negative) {...}
....
}
Even that was purely at client side, I'm confused how to deal with Objects/JSON serialization and how bodyParser acts for it.
You have not serialized the data in your request, it's still just a JavaScript object until you serialize it as JSON:
$.ajax({
type:"POST",
contentType: "application/json",
url:"/psychos",
data: JSON.stringify( this.pyscho )
})
So call JSON.stringify in order to serialize as JSON and then the body parser has something to parse.
app.post("/psychos", function(request, response) {
//change request.body.psycho to request.body
var psychologist = request.body
console.log(psychologist)
psicologosCollection.insert(psychologist, function(error, responseFromDB) {
if (error) {response.send(responseFromDB)}
console.log("Se ha insertado: "+ JSON.stringify(responseFromDB))
response.send(responseFromDB)
})
})