I'm writing an API in Node.JS to protect my API keys for a basic weather app SPA.
Initially my http requests got through fine. The next day (today), with no changes to the request, it fails and I am subjected to a 90-second delay before I receive an unhelpful ETIMEDOUT response.
connect ETIMEDOUT 2600:1407:3c00:d90::116:80
I tried switching to node-fetch and got similar results. I also tried a different api but got the same result, so it must be local to my program.
Can anybody see what's wrong here?
const express = require('express');
const app = express();
const PORT = 8080;
const http = require('http');
const fetch = require('node-fetch'); /* try using node-fetch */
app.use(express.json());
app.listen(
PORT,
() => console.log(`it's alive on http://localhost:${PORT}`)
);
/* wetter, german for weather */
app.get('/wetter', (req, res) => {
console.log('got a wetter request');
var city = req.query.city;
if(!city){
res.status(400).send({message: 'Specify a city!'})
}
console.log(`city: ${city}`);
//let url = `http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=${city}&aqi=no`;
/* weatherapi.com failing. Try weather.gov. */
let url = 'http://api.weather.gov/';
console.log(url);
http.get(url, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
try {
let json = JSON.parse(body);
// Do stuff.
console.log(json);
} catch(error) {
console.error('TRY error: ' + error.message);
};
});
}).on('error', (error) => {
console.error('GET error: ' + error.message);
})
/* http failing. Try node-fetch */
//let settings = { method: "GET", timeout: "1000" };
//fetch(url, settings)
// .then(res => res.json())
// .then((json) => {
// console.log(json);
// });
console.log('Done. Sending response.');
res.status(200).send({
city: `${city}`,
forecast: 'forecast-data'
})
});
Both http and fetch apis are working fine for me. Make sure you are using the right node version.
FYI I am using Node Version 18.17.1