Home > Mobile >  Printing a HTML JavaScript variable from an external js to an index.html file using fetch node.j
Printing a HTML JavaScript variable from an external js to an index.html file using fetch node.j

Time:07-19

Note: [new edits are at the bottom of the post]

Here is the actual website so you can actually test it, much better than having bits and pieces b/c there are so many things that can go wrong it seems! :D

https://j1m3.xyz/weather/index.html

https://j1m3.xyz/weather/index.js

At the moment my dev console is just showing index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1) so my guess is there is something going on with node-fetch? I have the "type": "module" https://j1m3.xyz/weather/package.json so not sure what else to do there atm.

Because I am still learning I'd rather not add an extra layer to the project including Express.js. I am sure at some point I will though as it seems to make a lot of things easier...What I am trying to do this using fetch, is instead of printing my javascript code to the console, which works just how I'd like to see it, I want to print it to an external html page.

Here is my JavaScript code:

index.js

import fetch from './node-fetch';

async function fetchWeatherJSON() {
    const response = await fetch('https://api.openweathermap.org/data/.../&appid={API-KEY}');
    const weather = await response.json();
    return weather;
}

fetchWeatherJSON().then(weather => {
document.querySelector("#weather").innerHTML = `Longitude: ${weather.coord.lon}`
    console.log(`Longitude: ${weather.coord.lon}`);
    console.log(`Latitude: ${weather.coord.lat}`);
    console.log(`Current Temp: ${weather.main.temp}`);
    console.log(`Feels Like: ${weather.main.feels_like}`);
    console.log(`Sunrise: ${weather.sys.sunrise}`);
    console.log(`Sunset: ${weather.sys.sunset}`);
    console.log(`City/State: ${weather.name}, GA`);
});

Inside fetchWeatherJSON().then(...) part I tried things like

document.querySelector("#weather").innerHTML = `Longitude: ${weather.coord.lon}`;

but none of those types of ways worked. I have no idea if there is just something I am doing wrong here as far as selectors or this isn't the best way (or any way) to do it.

I'd like to print this to an index.html page, here is a simple example of some HTML. It would be nice to be able to print whatever is shown the javascript console inside the opening an close <p> elements.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js Weather App</title>
</head>
<body>
    <h2>Node.js Weather App</h2>
    <div id="weather"></div>

    <script type="text/javascript" src="index.js"></script>
</body>
</html>

I have searched and got some resources but there's always something missing, out of date or requires me to add more modules which I am trying to avoid, at least for right now.

edit #1: I ran node index.js through the my terminal and got a module mmising error. So I corrected it to: import fetch from 'node-fetch'; and it got rid of that error and printed out the json from open weather via the console.log(weather); so that's good. It also gave me a better error, finally.

        document.querySelector("#weather").innerHTML = `Longitude: 
        ^
${weather.coord.lon}`
        
ReferenceError: document is not defined

But that error is only when I run node index.js so not sure about the error just yet. I reloaded the main page (index.html) and my chrome dev console still gives me Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

I was guessing (in a way) that the line above would take the string on the left and place it inside the #weather selector but maybe I am wrong, I maybe have to read up on it more, only so much time in a day though! :)

CodePudding user response:

This code cannot work. Not on node.js nor on the browser because:

  1. Node.js has no fetch built in, so you need an extra library for it. For this you use node-fetch. But in the same .js file you try to access DOM elements with document.. Dom elements does not exist in Node.js, only inside the browser.

  2. This code wont work, because usually you have an bundler like Vite or webpack that bundles your npm packages. Anyway, node-fetch is only made for Node.js, not for the browser.

The browser already has an built-in fetch.

CodePudding user response:

Set a console.log to check if "weather" has any value. Also, your QuerySelector is wrong:

document.querySelector("#weatherHTML")

CodePudding user response:

You are using the wrong type of query selector: document.querySelector("weatherHTML") will select elements named accordingly (<weatherHTML></weatherHTML>).

You should use document.querySelector("#weatherHTML") to select the element with the corresponding id.

This is also equivalent to document.getElementById("weatherHTML")

Using this principle, this is the new fetchWeatherJSON callback:

fetchWeatherJSON().then(weather => {
    console.log(`Longitude: ${weather.coord.lon}`);
    console.log(`Latitude: ${weather.coord.lat}`);
    console.log(`Current Temp: ${weather.main.temp}`);
    console.log(`Feels Like: ${weather.main.feels_like}`);
    console.log(`Sunrise: ${weather.sys.sunrise}`);
    console.log(`Sunset: ${weather.sys.sunset}`);
    console.log(`City/State: ${weather.name}, GA`);

    document.querySelector("#weatherHTML").innerHTML = `Longitude: ${weather.coord.lon}...`
});

  • Related