Is there a way for filer API endpoint JSON response? - javascript

I have an external API endpoint that uses basic authentication that I'm trying to find a specific key and/or value of from the JSON response.
Results:
hrefsOnly returns an array with two items.
[
"https://192.168.254.133/api/json/v2/types/volumes/1",
"https://192.168.254.133/api/json/v2/types/volumes/3"
]
Calling hrefsOnly[1] shows the following JSON response:
{ "content": {
"ancestor-vol-name": null,
"small-io-alerts": "disabled",
"last-refreshed-from-obj-name": null,
"small-iops": "0",
"wr-latency": "1738",
"obj-severity": "information"
}}
volumeInfo is undefined in my code is below:
const express = require('express');
const app = express();
const request = require("request");
const bodyParser = require('body-parser');
const auth = 'YWRtaW46WHRyZW0xMA==';
//Get Volume api endpoint values
var getVols = {
method: 'GET',
url: 'https://192.168.254.133/api/json/v2/types/volumes/',
headers:
{
'cache-control': 'no-cache',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Basic ${auth}`
}
};
//Get above api endpoint data
var volsData = {
method: 'GET',
url: 'https://192.168.254.133/api/json/v2/types/volumes/1',
headers:
{
'cache-control': 'no-cache',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Basic ${auth}`
}
};
var hrefsOnly = [];
var volumeInfo = [];
//GET request to parse hfref data only
request(getVols, function (error, response, body) {
var data = JSON.parse(body);
if (error){
console.log('error: ', error);
} else {
for(var i = 0; i < data["volumes"].length; i++){
hrefsOnly.push(data["volumes"][i].href);
}
}
});
app.get('/url', (req, res, next) => {
res.send(hrefsOnly);
});
// GET Volumes JSON response
request(volsData, function (error, response, body) {
var vols = body;
if (error){
console.log('error: ', error);
} else {
for(var elem in vols){
volumeInfo.push(vols);
}
}
});
app.get('/volume', (req, res, next) => {
console.log(volumeInfo["content"]);
res.send(volumeInfo["content"]);
});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(3000, () => {
console.log("Server running on port 3000");
});
I expect when I visit the page localhost:3000/volume to return the content section from the API. the page shows blank though.
console.log(volumeInfo[1]) shows the JSON data, but volumeInfo[1].content is undefined. Not sure what I'm doing to get 'undefined' as the result.

You declared an array var volumeInfo = []; but you're using it as a map res.send(volumeInfo["content"]);
TTo access an element inside an array, you need an index (integer). Try with res.send(volumeInfo[0].content);

Related

Why is my fetch() sending an empty JSON body?

I've been trying to send a JSON data using fetch but the backend receives an empty object.
In my Client JS I have
const user = "company1";
const username = "muneeb";
const data = {user, username};
fetch("http://127.0.0.1:3000/users/api/login", {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
console.log(response);
});
The server side has:
router.post('/users/api/login', async (req, res, next) => {
try {
// console.log(request.body);
const request = JSON.stringify(req.body);
let imageTitles = [];
console.log(request);
*its random from here on out but you get the idea*
await components.getImages(imageTitles);
const finalKey = imageTitles.join("");
let images = await components.output(req.body.user ,req.body.username);
res.send(components.jsonConverter(imageTitles, images)); //---Top priority
db.setPassword(req.body.user, req.body.username , finalKey);
} catch (err) {
console.log(err);
res.send(err).sendStatus(500);
};
})
A few things I have already tried :
It works perfectly in Insomnia(postman).
express.json() is present , it helped me go from undefined to blank JSON.
I have enabled cors settings.
That's it for now.
The body parser express.json will only be applied for requests with Content-Type: application/json. You have to add the content type to your fetch call:
fetch("http://127.0.0.1:3000/users/api/login", {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})

how to use request response in another request

I'm trying to use the first express request and response data to the second request, the problem is that both requests need to have their own body data in case I want to use them in the frontend node, is there any efficient approach to solve this issue.
in my below requests code, I must use the uploadlink from the first request to the second request.
const ThumbnailUploadlink = async (req, res) => {
const { videoId } = req.body;
const clientServerOptions11 = {
uri: `https://api.vimeo.com/videos/${videoId}/pictures`,
body: JSON.stringify({
name: videoId,
}),
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions11, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
const uploadLink = body.link;
console.log(uploadLink);
}
});
};
// uploadLink must take value from previous request
const ThumbnailUpload = async (req, res, uploadLink) => {
const { selectedFile } = req.body;
const clientServerOptions = {
url: `${uploadLink}`,
body: JSON.stringify({
name1: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
console.log(uploadLink);
} else {
const body = JSON.parse(response.body);
res.send(body);
console.log(uploadLink);
}
});
};

POST method returns empty object in both client and server

So I am building a recipe search engine and I want to transfer the user's choice of the category to the server so I can use it in API call. Here's some code :
CLIENT-SIDE
function getRecipes(category){
const categorySearch = category.alt;
let data = {
categoryChoice: categorySearch
}
console.log(data);
let options = {
method: 'POST',
headers: {
'Content-type': 'text/plain'
},
body: JSON.stringify(data)
}
const promise = fetch('/data', options);
console.log(promise);
}
SERVER-SIDE
const express = require('express');
const app = express();
const fetch = require('node-fetch');
require('dotenv').config();
const API_KEY = process.env.API_KEY;
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({ limit: "1mb"}));
app.post('/data', (request, response) => {
let data = request.body;
console.log(data);
response = "Got data";
console.log(response);
})
categorySearch and data variables definitely get what it should, I have logged in and it's working fine. Then whether I log promise in client-side or data in server-side I only get {}, any ideas?
Working with JSON content type.
Backend-Side should be returning data:
app.post('/data', (request, response) => {
let data = request.body;
let gotData;
if(data.categoryChoice == "option1")
gotData = {id:1, label:"val 1", q:data.categoryChoice};
else
gotData = {id:2, label:"val 123", q:data.categoryChoice};
response.json(gotData);
});
And the Client-Side:
let data = { categoryChoice: "option1" };
let options = {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(data)
}
const promise = fetch('/data', options);
promise.then(response => {
if (!response.ok) {
console.error(response);
} else {
return response.json();
}
}).then(result => {
console.log(result);
});
Your backend part should be returning a response for it to work the way you expect it.
You are only handling a POST request but you also need a get request.
app.get('/data', (request,response) => {
return response.json({
// JSON data here
})
})

Express routes giving 500 internal server

my server can't find the api's that i created in api directory. it leads to 500 internal server.
I have checked routes.js but i see that everything is right. i have an error.js file for file handling. Here's my code.
'use strict';
let router = require('express').Router();
// Middleware
let middleware = require('./controllers/middleware');
router.use(middleware.doSomethingInteresting);
// Tasks
let tasks = require('./controllers/tasks');
let createkeypairs = require('./controllers/createkeypairs');
let importaddress = require('./controllers/importaddress');
let getwalletinfo = require('./controllers/getwalletinfo');
router.get('/tasks', tasks.findAll2);
router.get('/createkeypairs', createkeypairs.findAll);
router.get('/importaddress', importaddress.findAll);
router.get('/getwalletinfo', getwalletinfo.findAll);
router.post('/buggyroute', tasks.buggyRoute);
// Error Handling
let errors = require('./controllers/errors');
router.use(errors.errorHandler);
// Request was not picked up by a route, send 404
router.use(errors.nullRoute);
// Export the router
module.exports = router;
now showing you my createkeypairs.js
'use strict';
let errors = require('./errors.js');
var request = require("request");
var options = { method: 'POST',
url: '127.0.0.1:18332',
headers:
{ 'Authorization': 'Basic bXVsdGljaGFpbnJwYzpHTmJ5enJhMnlHRjN4Ymp1cnluRTFucTlnV1ExRXV3OTFpYVBqSkt5TkJxdA==',
'cache-control': 'no-cache',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json' },
body: { method: 'createkeypairs', params: [], chain_name: 'tokenchain' },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log("working here ");
// res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
I think the problem is in createkeypair file.
Try this code once for your createkeypairs.js:
'use strict';
let errors = require('./errors.js');
var request = require("request");
let config = require('config');
var auth = 'Basic ' + Buffer.from(config.user + ':' + config.pass).toString('base64');
var url = config.url;
var chain = config.chain;
var options = { method: 'POST',
url: url,
headers:
{ 'cache-control': 'no-cache',
Authorization : auth,
'Content-Type': 'application/json' },
body: { method: 'importaddress', params: ["address"], chain_name: chain },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
Do tell me if it works or not.

difference between api call and on postman

I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?
Below is how i call speech api by node.js.
'use strict';
const request = require('request');
const subscriptionKey = 'MYSUBSCRIPTIONKEY';
const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
const options = {
uri: uriBase,
body: 'speech.wav',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey,
'Transfer-Encoding': 'chunked',
'Expect': '100-continue',
'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
You can try this
fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
if (err) throw err;
var options = {
host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
method: 'POST',
headers: { 'Content-Type': 'audio/wav' }
};
var req = http.request(options, function(res) {
// Handle a successful response here...
});
req.on('error', function(e) {
// Handle an error response here...
});
// Write the audio data in the request body.
req.write(data);
req.end();
});

Categories

Resources