Getting JSON Data into image format - node.js

I have this GET request I built to call Google APIS dot com to get an image of a house at a given address. It's all working fine. In Postman it displays the image from the body of the request. All good!
I converted the code to NodeJS REQUEST. Put that code into my project. It all works though the data returned is all �����JFIF������ like this in the BODY returned.
Can you point me to some resources or can you tell me in NODEJS how I get that into a Image type variable. I want to then display it using JSON code into Messenger Bot. I have the JSON code to send a IMAGE type back to Messenger - I just need to get the results of the GET above into a format in NODEJS that will work - like a PNG or JPG format.
This is the code I used from Postman CODE:
var options = { method: 'GET',
url: 'https://maps.googleapis.com/maps/api/streetview',
qs:
{ size: '450x450',
location: 'N108W15303%20Bel%20Aire%20Ln%2053022',
fov: '90',
heading: '235',
pitch: '10',
key: 'xxx' },
headers:
{ 'Postman-Token': 'xxx',
'Cache-Control': 'no-cache',
Accept: 'application/json' } };
requestGoogle(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The BODY var is is all ����JFIF��C
It displays great in the Postman App. so you are somehow converting it to display it - what I am looking for.
Any help would be appreciated - or direct me to a resource that can help that would be great.

Related

I am facing issue while reading request body in Azure function node js

In my azure function post call i am passing body like this
{
"license":{
"licensepolicy": "NA",
"metadata":{
"tenantname":"tenantname",
},
"licensetype":"type"
},
"customer":{
"name":"TEst User",
"emailaddress":"email",
"company":"test"
}
}
In my code I am accessing this request body like below
context.log(req.body.license);
Its giving undefined log, I don't know why but its working in normal node js code but in azure function its not working.
Please assist me if I am wrong somewhere
thanks in advance
Make sure to check your post method whether it contains the Header 'Content-Type': 'application/json'
headers: {
'Content-Type': 'application/json'
}
If you are not sending the Json response you have to convert that into Json object in your code to retrieve that information.
# convert request into Json object and access those informations.
const parsedData = JSON.parse(req)
context.log(parsedData.body.license);

How to follow a link in a get request header in Node.js Express

I am trying to retrieve paginated results from a 3rd party API after making an API call from my Node.js/Express server. I then want to send the data through to the client. I can retrieve the first page of results using the Request package and the following code:
var options = {
url: `https://theURL.com`,
headers: {
'authorization': `bearer ${user_token}`,
'user-agent': '***my details***'
}
}
function callback(error, response, body) {
if (!error) {
res.json({
data: body
});
} else {
res.send("an error occured")
}
}
Request(options, callback);
I understand that the response will contain a Link header which I should follow to get the next page's data and to retrieve the link header for the page after that. I repeat this process until I reach a blank link header, at which point all the pages of data have been retrieved.
Firstly, I don't know how to approach this task, should I be following all the link headers and compiling all the results on my server before transferring them to the client? Or should I send each pages worth of data to the client as I get it and then deal with it there?
Secondly, how can an appropriate solution be achieved in code?

postman POST request doesn't work in nodejs (accessing 3rd party API)

I've been playing around with some web scraping but I've run into an issue I can't figure out; Using a nodejs server (on my local computer) I cannot get passed a permission error barring me from accessing the data. What is confusing to me most is that using the chrome extension "Postman" I don't run into the permission errors, but using the code generated by postman, I do (as well as fiddling with variations of my own scratch code).
Do I have to be using a live server? Do I need to include some extra items in the headers that aren't being put there by Postman? Is there some layer of security around the API that for some reason Postman has access do that a local machine doesnt?
Any light that can be shed would be of use. Note that there is no public documentation of the SmithsFoodAndDrug API (that I can find), so there aren't necessarily APIKeys that are going to be used. But the fact that Postman can access the information makes me think I should be able to on a node server without any special authentication set up.
In Summary:
I'm looking at SmithsFoodAndDrug product information, and found the API where they are grabbing information from.
I figured out the headers needed in order to get local price information on products (on top of the json body format for the POST request)
Using postman I can generate the POST request and retrieve the desired API results
Using nodejs (and the code generated by postman to replicate the request) with both 'request' module and standard 'http' module request module I receive permission errors from the server.
Details: (assume gathering data on honeycrisp apples (0000000003283) with division-id of 706 and store-id of 00144)
http://www.smithsfoodanddrug.com/products/api/products/details
Headers are 'division-id' and 'store-id'. Body is in format of {"upcs":["XXX"],"filterBadProducts":false} where XXX is the specific product code.
Here are the Request Headers in postman. Here are the Request Body settings in postman. The following is a portion of the json response (which is what I want).
{"products": [
{
"brandName": null,
"clickListItem": true,
"countryOfOrigin": "Check store for country of origin details",
"customerFacingSize": "price $2.49/lb",
...
"calculatedPromoPrice": "2.49",
"calculatedRegularPrice": "2.99",
"calculatedReferencePrice": null,
"displayTemplate": "YellowTag",
"division": "706",
"minimumAdvertisedPrice": null,
"orderBy": "Unit",
"regularNFor": "1",
"referenceNFor": "1",
"referencePrice": null,
"store": "00144",
"endDate": "2018-09-19T00:00:00",
"priceNormal": "2.55",
"priceSale": "2.12",
"promoDescription": "About $2.12 for each",
"promoType": null,
...
"upc": "0000000003283",
...
}
],
"coupons": {},
"departments": [],
"priceHasError": false,
"totalCount": 1 }
When using the code given by postman to replicate the request, I get the error saying 'You don't have permission to access "http://www.smithsfoodanddrug.com/products/api/products/details" on this server.
Reference #18.1f3de93f.1536955806.1989a2b1.' .
// Code given by postman
var request = require("request");
var options = { method: 'POST',
url: 'http://www.smithsfoodanddrug.com/products/api/products/details',
headers:
{ 'postman-token': 'ad9638c1-1ea5-1afc-925e-fe753b342f91',
'cache-control': 'no-cache',
'store-id': '00144',
'division-id': '706',
'content-type': 'application/json' },
body: { upcs: [ '0000000003283' ], filterBadProducts: false },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
change headers
headers:
{
'store-id': '00144',
'division-id': '706'
//'content-type': 'application/json'
}

Sending file via POST using fs.createReadStream doesn't send the file

I have the following code. Issue is, the file isn't always getting caught by my server (hosted on DigitalOcean, not that that matters so much as I often couldn't even get it to work on my local vagrant machine).
It seems to work with smaller files, smaller images, however if I send a larger file (such as a full screen screenshot) my server is telling me that the request has been made but no 'image' has been found.
I had a look around for a way for createReadStream to return some kind of promise, in hopes that it would be as simple as it is still trying to read the image from the hard drive, but I've had no luck.
Worth mentioning that the image is being generated just before this happens, but this is being called in a callback so that shouldn't matter.
...
const capture = fs.createReadStream(filePath);
request.post({
url: UPLOAD_URL,
method: 'POST',
formData: {
'image': capture,
'token': this.token
},
headers: {
'User-Agrent': 'request',
'Content-Type': 'multipart/form-data'
}
}, (err, response, body) => {
...

Sending URL encoded string in POST request using node.js

I am having difficulty sending a url encoded string to the Stormpath /oauth/token API endpoint. The string is meant to look like this:
grant_type=password&username=<username>&password=<password>
Using Postman I was successful in hitting the endpoint and retrieving the data I want by providing a string similar to the one above in the request body by selecting the raw / text option. But when I generate the code snippet it looks like this:
var request = require("request");
var options = { method: 'POST',
url: 'https://<My DNS label>.apps.stormpath.io/oauth/token',
headers:
{ 'postman-token': '<token>',
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
host: '<My DNS label>.apps.stormpath.io',
accept: 'application/json' },
form: false };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Where did that string go? I would like some help in understanding the disconnect between knowing I sent a url encoded string to the API endpoint using Postman and not seeing it in the code generated by Postman. Because now I don't know how to reproduce a successful call to the endpoint in my actual app.
To me it seems like I should simply provide a body to the request, but the response comes out to be {"error":"invalid_request","message":"invalid_request"}. I have also tried appending the url encoded string to the url but that returns a 404 error.
I'm just now getting back into using an API and am not very experienced doing so.
The form data needs to be posted as an object, here is an example:
request.post('http://service.com/upload', {form:{key:'value'}})
Taken from this documentation:
https://github.com/request/request#forms
Hope this helps!

Resources