how do I use "Fetch" - javascript

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.

Related

sveltekit fetch function with ajax requests

In my sveltekit app I make AJAX calls to my api endpoints. For example:
+page.svelte
<script>
async function get_card() {
const url = '/api/card/?category=' + $page.params.slug;
const response = await fetch(url, {
method: 'GET',
})
const card = await response.json();
return card;
}
</script>
In the browser javascript console I get this warning:
Loading /api/card/?category=Neurology using `window.fetch`.
For best results, use the `fetch` that is passed to your `load`
function: https://kit.svelte.dev/docs/load#making-fetch-requests
But as far as I can tell, that fetch function is only accessible to me on the server, and I do not see a way to use it in a script that may run on the client (such as +page.svelte). I tried passing the function as part of the data object from load:
+layout.server.js
export const load = async ({ fetch, locals }) => {
return {
email: locals.user.email,
group: locals.user.group,
fetch: fetch
}
}
But, not surprisingly, that does not work since the function is not serializable.
Am I Doing It Wrong™, or should I just ignore the warning?
fetch is originally a browser API and SvelteKit defines it on the server as well, if it does not exist. The warning is there to tell you that you are creating another round trip to the server (one for the page and one for the data) when you possibly could have loaded the data on the server so it could be transmitted as part of the page (during server-side rendering).
If the code of your function is not executed right away, then this is a false positive (recent issue on this). I.e. if the data should be requested at a significantly later point, there is no way to bundle the request with the page.
(You are definitely not meant to pass on the fetch of load, you are supposed to use it to get the data.)

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)

Handling non JSON API in 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.

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.

Returning the output of an async function in a Hapi route handler

I'm working on a Twitch extension if anyone's familiar and started working off of one of their examples. I'm fairly new to JS with mostly a C# background so a lot of this is kinda foreign to me. Basically I've setup a hapi route and want my node server to make an API call to a different service and return a string that includes some of the data from the API response, which then gets inserted to an iFrame using an AJAX request. The API wrapper that I'm using uses async functions and when I call them inside the route handler the requests seem to time out from what I can tell from looking at the request in chrome's devtools. Not sure if the API calls are just taking too long or something along those lines? Here's a link to the API wrapper I'm using: https://www.npmjs.com/package/smashgg.js?activeTab=readme
I suspect I'm missing something with the async/await syntax, I don't really fully understand how they work yet. Ideally I'd like to have the code that returns the output string in it's own method but for simplicity I've just copied the example but I'm getting the same results. This code runs fine in its own file.
Here's the route definition:
server.route({
method: 'GET',
path: '/bracket/query',
handler: bracketQueryHandler
});
and the route handler method:
async function bracketQueryHandler(req){
const payload = verifyAndDecode(req.headers.authorization);
const { channel_id: channelId, opaque_user_id: opaqueUserId } = payload;
const currentBracket = channelBrackets[channelId] || initialBracket;
let tournamentSlug = 'function-1-recursion-regional';
let eventSlug = 'melee-singles';
let meleeAtFunction = await Event.get(tournamentSlug, eventSlug);
let sets = await meleeAtFunction.getSets();
let phaseGroups = await meleeAtFunction.getPhaseGroups();
let setString = "";
for(var i in sets){
setString += "\n" + sets[i].getFullRoundText() + " : " + sets[i].getDisplayScore();
}
console.log(setString);
return setString;
}
You need to wait for the result of the async function bracketQueryHandler to resolve. This should be as simple as as adding an await in your route handler.
server.route({
method: 'GET',
path: '/bracket/query',
handler: await bracketQueryHandler
});
That said I would normally use a construction like..
server.route({
method: 'GET',
path: '/bracket/query',
handler: async (request, h) => {
return await bracketQueryHandler(request)
}
});
This construction is consistent with the docs. https://hapijs.com/tutorials#routes
Some reading on async / await https://medium.freecodecamp.org/how-to-master-async-await-with-this-real-world-example-19107e7558ad
Getting familiar with this syntax and the Promise is quite necessary using Hapi 17 and above.

Categories

Resources