Cannot get simple weather feteching code to work - javascript

I'm using the following code
try {
const response = await fetch(endpoint);
if(response.ok) {
jsonResponse = await response.json();
return jsonResponse;
}
} catch(error) {
console.log(error.message);
}
to fetch weather info from openweathermap. When I run the program locally on my computer or using a local server with VSC I get a "NetworkError when attempting to fetch resource." error caught. When I input the URL (https://api.openweathermap.org/data/2.5/weather?q=Madrid&appid=...)straight into the web browser it shows me the content without any issues. I can't for the life of me figure out what I'm doing wrong. What am I missing? (the link is missing the api key for obvious reasons, but it's written correctly in the code)

Related

FetchError: request to url failed, reason ECONNREFUSED crashes server despite try catch being in place

The problem
FetchError: request to https://direct.faforever.com/wp-json/wp/v2/posts/?per_page=10&_embed&_fields=content.rendered,categories&categories=638 failed, reason: connect ECONNREFUSED
I'm doing some API calls for a website using fetch. Usually there are no issues, when a request "fails" usually the catch error gets it and my website continues to run. However, when the server that hosts the API calls is down/off, my fetch API calls crash the website entirely (despite being on a try catch loop).
As far as I'm concerned, shouldnt the catch block "catch" the error and continue to the next call? Why does it crash everything?
My wanted solution
For the website to just move on to the next fetch call / just catch the error and try again when the function is called again (rather than crashing the entire website).
The code
Here is an example of my fetch API call (process.env.WP_URL is = https:direct.faforever.com )
async function getTournamentNews() {
try {
let response = await fetch(`${process.env.WP_URL}/wp-json/wp/v2/posts/?per_page=10&_embed&_fields=content.rendered,categories&categories=638`);
let data = await response.json();
//Now we get a js array rather than a js object. Otherwise we can't sort it out.
let dataObjectToArray = Object.values(data);
let sortedData = dataObjectToArray.map(item => ({
content: item.content.rendered,
category: item.categories
}));
let clientNewsData = sortedData.filter(article => article.category[1] !== 284);
return await clientNewsData;
} catch (e) {
console.log(e);
return null;
}
}
Here's the whole code (this whole thing is being called by express.js in line 246 (the extractor file).
Extractor / Fetch API Calls file
https://github.com/FAForever/website/blob/New-Frontend/scripts/extractor.js
Express.js file in line 246
https://github.com/FAForever/website/blob/New-Frontend/express.js#:~:text=//%20Run%20scripts%20initially%20on%20startup

Catching Error With Custom Rest API For FireStore Javascript

I have been watching a tutorial on making a Rest API for Firestore which appears to work but I cannot figure out how to catch an error.
The code below basically uses an end point to retrieve a document id from the firestore database.
The client uses javascript fetch to call the API.
I am trying to workout how to return something back to the client from the API if the document id is not there. I thought I might get a 404 status returned but I always get status 200.
This is the API code I used
app.get("/api/read/:id", (req, res) => {
(async () => {
try {
const document = db.collection("users").doc(req.params.id);
let product = await document.get();
let response = product.data();
return res.status(200).send(response);
} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
})
I'm fairly certain that the 404 message is for the server itself not being found (though I do need to brush up on my error codes).
However, if you're looking to check to see if a document exists there's a command specifically for that demonstrated in the examples in the firebase docs

read file from computer javascript and print console.log its not print

when i debug this code in to chrome console then its not show any output or alert! please help me to complete this code! i need to get read my read.txt file text in to console.log....
the code was i try one is shows below.
function loadText() {
fetch('C:\Windows\Temp\read.txt')
.then(function(response){
return response.text();
})
.then(function(data){
console.log(data);
alert(data)
})
.catch(function(error){
console.log(error);
alert(data)
})
}
Try below code and indicate your directory like below
async function fetchText() {
let response = await fetch('../demo.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK
if (response.status === 200) {
let data = await response.text();
console.log(data);
// handle data
}
}
fetchText();
This seems like a duplicate of this issue - AJAX request to local file system not working in Chrome?
The problems are the same, however you are using the fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) not an XMLHttp request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
When i run loadText i get the following error:-
Fetch API cannot load . URL scheme must be "http" or "https" for CORS request.
You cannot make requests to the filesystem in Chrome. However you can disable Chrome security using flags (--allow-file-access-from-files)
see - Allow Google Chrome to use XMLHttpRequest to load a URL from a local file however this is not advised.
You will also need to update your path in the fetch function by prefixing with file:/// this tells it to look in the file system, and changed the protocol from http or https.

readableStream is locked while using .json()

everyone!
I got a problem: I'm trying to validate registration form. Totally, it works ok, but I need to validate form via server. In my case, for example, I need to figure out if email is already taken.
I tried to fetch and async/await syntax, but problem is still the same:
DOMException: "The operation was aborted. "
The way I understand it right now is readableStream (what actual response body is) is locked. So the wrong error is thrown, and I cannot get server response.
try {
const response = await fetch(options.url, options.requestOptions);
const body = await response.json();
if (options.modifyDataCallback instanceof Function) {
body.data = options.modifyDataCallback(body.data);
}
return body.data;
} catch (error) {
throw error;
}
How do I see the solution? I send request and recieve some server error like
code: email_in_use
message: Email '...' is already in use.
Then I need to throw error and catch it in other place in order to show corresponding error message to client.
In browsers network tab I do receive what I want to receive, but can't get the same JSON-response in my code.
Google chrome provided more information: net::ERR_HTTP2_PROTOCOL_ERROR 200.
And the problem was on backend. It is written in C# and API method returned Task. The problem was solved by adding async/await for this method.

javascript fetch does not catch 404 error

I have an app with uses a fetch to retrieve information from a 3rd party API. I am calling the API via cors-anywhere-herokuapp.com. When I call the API with valid data, I am able to retrieve the API response and pick up the data I need to pick up. When I call the API with invalid data, the API returns a 404 server error. I am forcing invalid data so I can code to catch this situation. My problem appears to be that the fetch does not catch the 404 error. I have tried coding to inspect the return.status but to no avail. I tried testing return.ok and that didn't work either. This is the code I am executing:
function showProduct(barcode) {
let url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=" + barcode + "&key=mj1pm32ylcctxj1byaia85n9dk2d4i";
url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=5000159459211&key=mj1pm32ylcctxj1byaia85n9dk2d4i";
const options = { method: 'GET' };
fetch( url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
console.log("fetch failed")
}
else
{
//inspect the data that the WebAPI returned
document.getElementById("showScanner").style.visibility = "hidden";
document.getElementById("scanner-container").style.visibility = "hidden";
document.getElementById("showProductDiv").style.visibility = "visible";
document.getElementById("productManufacturer").innerHTML = myJson.products[0].manufacturer;
document.getElementById("productName").innerHTML = myJson.products[0].product_name;
document.getElementById("productDescription").innerHTML = myJson.products[0].description;
Quagga.stop();
}
});
}
and this is what I see in the debugger when I execute the code
When I look at the debugger network tab, and click on Headers, I see this:
So, my question is, how do I capture the status code?
According to the documentation on fetch's response, you should be able to testthe status code of the response that fetch's Promise resolves to using response.status.
Note that although it's unintuitive, the Promise fetch returns only rejects when there's a connection error. If the connection succeeds and there's a response, this promise will resolve with the response, even if the status code is non-200.

Categories