Handling non JSON API in Javascript - javascript

So I am trying to get a circulating supply number of a token and use the API to do a further calculation with it.
All I could find was people handling JSON outputs but this is just a plain output:
https://avascan.info/api/v1/supply?q=circulatingSupply
Anyone that can help me how I can fetch this amount and use it to further do calculations with?

You can use the fetch API, which have a text method on it's response, for example:
const BASE_URL = 'https://avascan.info/api/v1/supply?q=circulatingSupply';
async function getCirculatingSupply() {
const response = await fetch(BASE_URL);
const data = await response.text();
return Number(data);
}
getCirculatingSupply().then(console.log);
Keep in mind that maybe you will have problems with CORS, as I had testing this API, so maybe you will need to use a proxy server like cors-anywhere to bypass this problem.

Related

Fetch Location using google Api

I am trying to get the latitude and longitude of user location using google api
I have tried doing this using the fetch method in javascript but I do not get any response. There's no error or anything.
The documentation says to fetch it this way:
https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY
How I fetch it:
const res = await fetch(https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY)
const response = await res.json()
When I first did it like above I got an error because it returned nothing which I found out after console.logging res.text()
I do not know what I'm doing wrong In the documentation they equally said something about including Request body but it's optional, So I have no need to include it. Please do you have any ideas on what I'm doing wrong?
I believe you need to send this as a POST request according to the documentation you linked. By default fetch sends a GET request.
To do that you just need to pass in the request type to the fetch function
const response = await fetch(<URI>,{method:'POST'});
const res = await response.json()
console.log(res)

How to write requests and fetch

I need help how to correctly write a GET and POST request in my server (index.js) and how to properly write the fetch in App.js.
I have read threads here on Stackoverflow and I have searched for information on how to write requests and fetches but I find it very difficult how to add the examples to my own code. I have tried different solutions for three weeks but getting nowhere it feels like. So, please help. I feel like this should not be that difficult, but for some reason it is. I have no one to ask for help other than here.
I'm using the URL http://localhost:8080/reviews
Is this how I write or do I have to add anything? (in Index.js)
app.get("/reviews", (request, response) => {
response.status(201).json
});
app.post('/reviews', async (request, response) => {
response.status(201).json
});
In App.js I want to create a fetch where I GET all the existing reviews that are written (none at the moment since the page isn't done yet) and I want to be able to POST new reviews. When I post a new review I want the page to load and update with the new and all the other written reviews.
I have something like this at the moment, but I don't know what the last parts should be?
const reviewsURL = "http://localhost:8080/reviews"
export const App = () => {
const [existingReviews, setExistingReviews] = useState([])
const [newReview, setNewReview] = useState('')
const fetchReviews = () => {
fetch(reviewsURL, {'
// WHAT ELSE TO WRITE HERE ???
useEffect(() => {
fetchReviews();
}, []);
const postReview = (event) => {
event.preventDefault();
fetch(reviewsURL, {
method: 'POST',
// WHAT DO I WRITE HERE ???
}
return (
<>
<NewReview
newReview={newReview}
setNewReview={setNewReview}
handlesubmit={postReview}
/>
{<AllReviews
allReviews={existingReviews}
/>}
</>
)
}
In express.js, response.status(201).json is not the way to return a JSON response. .json is a function, so you would pass it a JSON-ifiable object, response.status(201).json(resultsArray); or something like that.
A lot of people prefer to use a library for making requests, rather than using fetch. Axios is a common favourite, and lots of people find it much easier to use.
If you'd prefer to use fetch over an easier library, that's fine, fetch is still simple enough to get going with. Here's some documentation on how to use fetch
Of note: the fetch(url) function returns a promise, so you'll either .then the returned promise, or await it inside an async function. If you're expecting a JSON response, the patterns in the example code in the docs require an extra step to get the content:
const result = await fetch(url);
const data = await result.json();
That's for a GET request, but the docs also show how to get going with POST requests.

how do I use "Fetch"

class Fetch {
async getCurrent(input) {
const apiKey = "my_api_key";
// make request to url
const response = await fetch(
`https:/api.openweathermap.org/data/2.5/weather?q=${input}&appid=${apiKey}`
);
const data = await response.json();
console.log(data);
return data;
}
}
above is a snippet of code, can someone point me to the direction of the error?
I'm assuming you are running this code in Node.js, right?
If it's in the browser, you shouldn't have any issue since the fetch() API is implemented in the browser.
If you are running in Node.js you can use node-fetch which is a great implementation of fetch in Node.js.
Your code works fine. Problem can be in that how you call function.
You need to create an object, outside the class and call the function.
let f = new Fetch();
f.getCurrent("Kiev");
You can`t use variable name fetch because this name is reserved.

shorten axios text/html response

I am sending an Axios request to a web page for scraping a little string off of it, but the returned response is a large html, and I only need a little part of it, is there a way to somehow shorten the response so I can save data and make the request faster?
const longHtml = await axios.get('https://example.com');
const shortHtml = longHtml.data //get short data here
If I understand what your trying to do, you wan't to stop the request when you find the data you want, you could use htmlparser2 and feed it a stream from axios and then register listeners and when you get the element you need you can end the stream.
Web scraping is a technique used for retrieving data from websites. You fetch the page's contents, and after that extract the data you need from the page.
here an example by using axios and cheerio
const axios = require("axios")
const cheerio = require("cheerio")
async function fetchHTML(url) {
const { data } = await axios.get(url)
return cheerio.load(data)
}
const $ = await fetchHTML("https://example.com")
// Print the full HTML
console.log(`Site HTML: ${$.html()}\n\n`)
// Print some specific page content
console.log(`First h1 tag: ${$('h1').text()}`)

axios.all concurrent request GET or POST only

Going through the axios docs, I'm trying to figure out if the axio.all construct for making concurrent requests works when the request are not all get request i.e can it work with a mix of GET and POST requests.
You can try performing multiple requests with your Axios client and using Promise.all to wait on the result of all your requests.
Here's an example using JavaScript:
const promiseGet = axios.get('/user?ID=12345')
const promisePost = axios.post('/user', { some: data })
const [responseGet, responsePost] = await Promise.all(promiseGet, promisePost)
Note that you should handle the possible errors (it's not described in the example above!)

Categories

Resources