I ran the following code in node js
const request = require("request");
const GetUserInventory = {
method: 'GET',
url: 'https://api-trade.opskins.com/ITrade/GetUserInventory/v1/',
qs: { uid: '3192035', app_id: '1' },
json: true
};
request(GetUserInventory, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The output I got is the following. Here the values of the strings are not displayed. That is, they are displayed as [object] How do I get the desired output as stated in the picture?
{
status: 1,
time: 1536729167,
current_page: 1,
total_pages: 1,
response: {
items: [
[Object]
],
total: '1',
items_in_active_offers: null,
user_data: {
username: 'Mowrish gamdom.com',
avatar: 'https://steamcdn-a.opskins.media/steamcommunity/public/images/avatars/d7/d7cf2c088d4398bed904ae540b36211e1af202f2.jpg'
},
sort_parameters: [
[Object],
[Object],
[Object],
[Object],
[Object],
[Object]
]
}
}
The output, that I expect is as follows. How to get this output?
I have tried JSON.parse of body before console.log() instead of json: true value in GetUserInventory. It didn't work. And Also, I tried JSON.stringify of body. The same happened with it too
Try following if you want the output same as in screenshot you posted
request(GetUserInventory, function (error, response, body) {
if (error) throw new Error(error);
obj = JSON.stringify(body);
console.log(obj);
});
you have issue with response body. so there may be you have not set content-type when you call API.
The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.
pass content type in header:
Content-type: application/json; charset=utf-8;
so your response will be in JSON format you can access it.
or you can try this, this will also works.
obj = JSON.parse(JSON.stringify(body));
Related
I have a nest controller which accepts the following DTO, One of the parameters should be a buffer which is read from file
It suppose to read bin file
interface LoadFileRequest {
targetIp: string;
fileBuffer: Buffer;
user: User;
}
interface User {
username: string;
password: string;
}
#Controller('loader')
export class KeyLoaderController {
#Post('load')
async load(#Body() body: LoadFileRequest, #Req() request) {
console.log(body);
console.log(request);
}
}
My code for testing the controller:
import axios from "axios";
import fs from "fs";
import FormData from "form-data";
let headersList = {
Accept: "*/*",
};
let formdata = new FormData();
formdata.append("targetIP", "10.10.1.145");
formdata.append(
"user",
JSON.stringify({
username: "user",
password: "auth",
})
);
formdata.append("fileBuffer", fs.createReadStream("test.bin"));
let bodyContent = formdata;
const url = "http://localhost:3000/loader/load";
let reqOptions = {
url,
method: "POST",
headers: headersList,
data: { bodyContent },
};
axios.request(reqOptions).then(function (response) {
console.log(response.data);
});
At the controller this is the request body i get
{
bodyContent: {
_overheadLength: 380,
_valueLength: 48,
_valuesToMeasure: [ [Object] ],
writable: false,
readable: true,
dataSize: 0,
maxDataSize: 2097152,
pauseStreams: true,
_released: false,
_streams: [
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="targetIP"\r\n' +
'\r\n',
'10.10.1.145',
null,
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="user"\r\n' +
'\r\n',
'{"username":"user","password":"auth"}',
null,
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="fileBuffer"; filename="test.bin"\r\n' +
'Content-Type: application/octet-stream\r\n' +
'\r\n',
[Object],
null
],
_currentStream: null,
_insideLoop: false,
_pendingNext: false,
_boundary: '--------------------------092840744027446269037569'
}
}
How can i get the body in the form of object with only the attrbutes of the DTO?
Eventually i got a method which recived the same type of object and i want to call it like this:
#Controller('loader')
export class KeyLoaderController {
#Post('load')
async load(#Body() body: LoadFileRequest, #Req() request) {
return await loadFile(body);
}
}
EDIT:
I changed the code a bit and now if i send the request from VS code thunder client it works fine(sort of):
#Controller('loader')
export class KeyLoaderController {
#Post('load')
#UseInterceptors(FileInterceptor('fileBuffer'))
async load(#Body() body, #UploadedFile() file) {
console.log(body);
console.log(file);
}
}
When I send this way (The code on the right is the generated code by the extension, Which does not act the same way when I use it):
This is the body and file I get:
[Object: null prototype] {
targetIP: '10.10.1.145',
user: '{ "username": "user", "password": "0123456789"}'
}
{
fieldname: 'fileBuffer',
originalname: 'test.bin',
encoding: '7bit',
mimetype: 'application/octet-stream',
buffer: <Buffer ... ... 119 more bytes>, size: 169
}
But when i take the code i generated in VS code thunder client (which is at axios request in this post) I still get the body like before (again, as mention in the post)
If you're sending a multipart/form-data request, you need a form data body parser installed on the server. You can either use the FileInterceptor (or one of the derivatives of it), or bind multer as a middleware for the entire server. This will allow for the parsing of multipart/form-data requests.
In your axios call, remove the brackets around bodyContent so it becomes data: bodyContent. You aren't sending an object of form data you are just sending formdata itself
I'm getting APN Invalid parameter: JSON must contain an entry for 'default' or 'APNS_SANDBOX'. the log is here
And the code block is here:
how to fix this? this is built in scala lift framework.
This is the example in javascript. In the same way, we have to use. Need to use cases for
1.APNS_SANDBOX
2.APNS
3.default
// Setup SNS Client
const snsClient = new SNS();
// whatever your full endpoint arn is. (from createPlatformEndpoint)
const endpointArn = 'arn:aws:sns:...';
// any extra data you want passed along with the message
const payload = {
someCustomKey: 'someCustomValue'
};
// send it
snsClient.publish({
TargetArn: endpointArn,
MessageStructure: 'json', // so we can put in a custom payload and message
Message: JSON.stringify({
default: `DEFAULT MESSAGE ${message}`,
APNS_SANDBOX: JSON.stringify({
aps: {
alert: `IOS Sandbox SPECIFIC MESSAGE ${message}`,
},
payload,
}),
APNS: JSON.stringify({
aps: {
alert: `IOS Prod SPECIFIC MESSAGE ${message}`,
},
payload,
}),
}),
}).promise().then(() => {
console.log('Notification sent!');
}).catch((err) => {
console.log('Failed to send with:', err);
});
Used this link for reference
Wondering if anyone can help me with this - pretty much novice in scripting and not sure if I'm doing it right. I need to get an object from this JSON string and it keeps giving me "undefined" error.
Here's the JSON:
`
{ data:
[ { type: 'gif',
id: 'Cmr1OMJ2FN0B2',
slug: 'hello-Cmr1OMJ2FN0B2',
url: 'https://giphy.com/gifs/hello-Cmr1OMJ2FN0B2',
bitly_gif_url: 'https://gph.is/2bZufS7',
bitly_url: 'https://gph.is/2bZufS7',
embed_url: 'https://giphy.com/embed/Cmr1OMJ2FN0B2',
username: '',
source: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
rating: 'g',
content_url: '',
source_tld: 'www.fanpop.com',
source_post_url: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
is_indexable: 0,
import_datetime: '2016-09-05 13:48:36',
trending_datetime: '2017-09-19 14:26:18',
images: [Object],
title: 'bom dia hello GIF' } ],
pagination: { total_count: 2516, count: 1, offset: 0 },
meta:
{ status: 200,
msg: 'OK',
response_id: '5a28576867382f644dc7d33b' } }
`
And here's my HUBOT script:
`
robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) ->
api_url = 'https://api.giphy.com'
path = '/v1/gifs/search'
url = "#{api_url}#{path}"
robot.http(url)
.query
q: "nono+penguin"
rating: 'g'
limit: 1
fmt: 'json'
.header('api_key', giphyAuthToken)
.header('Content-Type', 'application/json')
.get() (err, res, body) ->
# error checking code here
if err
console.log err
else
data = JSON.parse(body)
console.log data #this prints above data
console.log "success....got giphy response"
console.log data.images.original.url #This is giving error that original is undefined
process.exit(1)
`
Wondering how can I access this "images" object from Giphy's response.
Thanks
The data field in your object is an Array so you need to put the index in order to access the content, i.e.
data = JSON.parse(body)
console.log data[0].images
I am new to NodeJS and trying to figure out how to load some xml data from a REST service and convert it to JSON so I can afterwards load it into my view.
I'm trying to do so querying with Hapi API and loading it into an xml parser then convert it to JSON.
Doing the following seems loading correctly the xml object and when printing it it actually shows me some JSON. Does it mean that I don't need to convert to JSON anymore?
const server = new Hapi.Server();
...
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
Request.get('http://ws.seloger.com/search.xml?&idtt=2&idtypebien=2,1&ci=750056&pxmax=400000&tri=initial&naturebien=1,2&surfacemin=65search.xml?',
function (error, response, body) {
if (error) {
throw error;
}
var parse = require('xml-parser');
var inspect = require('util').inspect;
var obj = parse(body);
console.log(inspect(obj, { colors: true, depth: 4 }));
Note that the JSON displayed is also not what I am looking for, ie. showing the details with attributes, children, etc.:
{ declaration: { attributes: { version: '1.0', encoding: 'UTF-8' } },
root:
{ name: 'recherche',
attributes: {},
children:
[ { name: 'resume',
attributes: {},
children: [],
content: '....' },
However looking for something more like this (might be just a different representation)
So I figured out that my issue seemed to have been related to the parser itself. Using this one I get what I need:
var parseString = require('xml2js').parseString;
parseString(body, function (err, jsonData) {
reply.view('index', { result: body });
});
With Azure Functions, what do you need to do to return a JSON object in the body from a function written in node.js? I can easily return a string, but when I try to return a json object as shown below I appear to have nothing returned.
context.res = {
body: jsonData,
contentType: 'application/json'
};
Based on my recent testing (March 2017). You have to explicitly add content type to response headers to get json back otherwise data shows-up as XML in browser.
"Content-Type":"application/json"
res = {
status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
Full Sample below:
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
context.log(context);
if (req.query.name || (req.body && req.body.name)) {
res = {
// status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
}
else {
res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done(null, res);
};
If your data is a JS object, then this should just work, e.g.
module.exports = function(context, req) {
context.res = {
body: { name: "Azure Functions" }
};
context.done();
};
This will return an application/json response.
If instead you have your data in a json string, you can have:
module.exports = function(context, req) {
context.res = {
body: '{ "name": "Azure Functions" }'
};
context.done();
};
Which will return an application/json response because it sniffs that it is valid json.
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.query.name || (req.body && req.body.name)) {
context.res = {
// status: 200, /* Defaults to 200 */
body: {"data":"Hello"},
headers: {
'Content-Type': 'application/json'
}
};
}
else {
// res = {
// status: 400,
// body: "Please pass a name on the query string or in the request body"
// };
}
context.done(null,res);
I would like to add one more point. Apart from making the body: a JSON object, the request should also contain proper headers telling server what content type we are interested in. I could see that same Azure function when just invoked via browser using URL gives XML response, but when invoking from script or tools like Postman it gives JSON.
I feel like the answer has been given but it hasn't been clearly presented so I thought I'd answer as well in case it will help anyone coming behind me. I too have created a function that most definitely returns a Javascript object but if I copy and paste the URL in the Azure Function UI and just open a new tab in Chrome and try to view the output, I actually get back an XML document that tells me there's an error (not surprising there's an error as many characters in the Javascript would have blown up the XML). So, as others have mentioned, the key is sending the appropriate headers with your request. When you copy/paste the URL into your browser, the browser is sending a request header that looks similar to this:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
When that happens, you see the XML return as described in this link:
https://github.com/strongloop/strong-remoting/issues/118
In order to get around this problem and see what the data would look like with a JSON request, either use a utility like Postman:
https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
Accept: application/json
Or use a CURL command and pass in the proper Accept header.
As you can see in the screenshot above, when I provided the proper header, I get back the JSON response I would expect.
You can also use JSON.stringify() to make a valid json string out of your js-object:
jsonData = { value: "test" }:
context.res = {
body: JSON.stringify(jsonData)
};