Fetch Location using google Api - javascript

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)

Related

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 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.

Fetch API (Javascript) Works Only When Debugged (Breakpoints)

I am attempting to retrieve JSON from an external source - Open Weather Map and I'm using the Javascript Fetch API to generate the request. I should be returned the current weather at a location via JSON that I can parse from the Open Weather Map API. When I'm debugging my applications and I have breakpoints on the fetch statement the request is sent and I receive a prompt response from the API. After I remove the breakpoints I receive the following message from the Firefox Developer Edition console TypeError: NetworkError when attempting to fetch resource., the Google Chrome console doe not log an error but I can see that a new network request was not generated.
const submitButton = document.querySelector('.submit-zip-button');
const APIKEY = 'REDACTED';
function parseWeather(currentWeather){
let currentTemp = currentWeather.main.temp;
let currentWeatherDescription = currentWeather.weather[0].description;
let weatherIconCode = currentWeather.weather[0].icon;
}
function getWeather(zipNum){
let weatherData = new Object();
fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zipNum},us&units=imperial&appid=${APIKEY}`)
.then(response => response.json())
.then(data => {
console.log(data);
weatherData = data;
parseWeather(weatherData);
});
}
submitButton.addEventListener('click', function(event){
event.stopPropagation();
let zipcode = document.querySelector('#zipcode-input');
zipcode = Number(zipcode.value);
getWeather(zipcode);
Does anyone have any tips or material I can read to better understand what's going on? I've read the Fetch MDN Page and used their example code as the basis of my fetch function.
I see a fetch, but no async / await, or any other way of waiting for the request to finish.
JS won't wait for your request to finish, it will just continue running. By the moment the request is finished, the execution of that code will be long gone.
There is a similar post right here and also a more detailed explanation of why and how to await a request right here.
If you make breakpoints, you will slow down the execution of the program, and at that moment it will be able to finish the request, having enough time. That's why in the debug mode it works. In production, it will take no time to await anything, until you tell him to.

why is that making GET request with search param won't return 404 even when the no resources have been found

I encountered this weird problem when experimenting with JavaScript's URL object
here is the demo : https://codesandbox.io/s/fervent-wilbur-15kyt?file=/src/index.js
so the endpoint is https://jsonplaceholsdsdsdder.typicode.com/todos/,
The key id can be integer as its value. So https://jsonplaceholder.typicode.com/todos/?id=4 is valid. and https://jsonplaceholder.typicode.com/todos/?id=dsdsd is not valid.
I found that using Fetch to make the request https://jsonplaceholder.typicode.com/todos/?id=4 will still return a response with a status code 200.
const inputEl = document.querySelector("#input");
const endpoint = new URL("https://jsonplaceholder.typicode.com/todos/");
inputEl.addEventListener("input", async e => {
const { value: text } = e.target;
endpoint.searchParams.set("id", text);
const repsonse = await fetch(endpoint).catch(console.error);
const data = await repsonse.json();
console.log(repsonse.status); // 200
console.log(data); // []
});
However if we construct the URL directly like this
https://jsonplaceholsdsdsdder.typicode.com/todos/dd. this will actually return a response with 404 status code.
search params are not a part of the resource location. They are optional and have to be manually accessed by the server processing the request.
https://jsonplaceholder.typicode.com/todos/ is a valid resource location that has been set up by jsonplaceholder.com.
https://jsonplaceholder.typicode.com/todos/?id=4 is a valid resource location because anything after the question mark (?) is a parameter and parameters are not considered to be apart of the resource location so it is still valid.
https://jsonplaceholsdsdsdder.typicode.com/todos/dd is not a valid resource location because jsonplaceholder.com has not exposed a resource with that path.
This is because of the way the API works server side.
If you try and use that route, you'll get the 404 error because that specific route wasn't found.
If you use the searchParams.set method, it's just a parameter that the backend will use to filter the full list of todos, in which case the call was made successfully, hence the 200 response code. but the response results were empty, hence the empty array [].

Data part of Response is a long script instead of desired json object

I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.
I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.
axios......then(function(response){
console.log(response.data);
})
Initially what i did was
var res = axios.get('/allUsers');
console.log(res)
That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.
What should be done to get the list of the users. That list i will be using to update my UI.
Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.
axios.get('some_url')
.then(res => res.json())
.then(data => {
// do something with the data
}).catch(err) {
conosole.error(err);
}
if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do
axios.get('some url').then(res => {
// do something in here with the data here
})
also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently
as an "Edit" you could also handle this with async await so you dont end up in callback hell
async function fetchData() {
try {
const res = await axios.get('some url');
// next step might not be necessary
const data = await res.json();
// do something with the data
console.log(data); // if converting it was necessary
console.log(res); // if not converting
} catch (err) {
console.error(err);
}
}

Categories

Resources