Запрос данных через строку браузера с локального сервера, полученых с арi
Создаю локальный сервер который должен принимать запросы вида (http://localhost:3000/rates?currency=ethereum) в строку ввода браузера и выдавать курс этой валюты в usd. не понимаю где ошибся в логике и в синтаксисе
const http = require('http');
const https = require('https');
const express = require('express');
var rank = '';
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
const options = {
host: 'api.coincap.io',
path: '/v2/assets?',
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
};
https.request(options, (response) => {
let str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
const { priceUsd } = JSON.parse(str).data[rank-1];
res.end('"usd": ', priceUsd);
});
const app = express()
app.get('/', function (request, response) {
response.send('<h1>Курс</h1>')
});
app.use('/rates', function (request, response) {
let id = request.query.currency
let PriceUsd = request.query.PriceUsd
response.send(
'<h1>Инфо</h1><p>id=' +
currency +
'</p><p>PriceUsd=' +
PriceUsd +
'</p>'
)
});
}).end();
});
server.listen(3000, '127.0.0.1');
Ошибка:
const { priceUsd } = JSON.parse(str).data[rank-1]; ^ TypeError: Cannot destructure property 'priceUsd' of 'JSON.parse(...).data[(rank - 1)]' as it is undefined. at IncomingMessage. (C:\Users\Галина\myapp\currency.js:28:21) at IncomingMessage.emit (node:events:525:35) at endReadableNT (node:internal/streams/readable:1358:12) at processTicksAndRejections (node:internal/process/task_queues:83:21)