1

I'm trying to weather Api app using node, express and Axios in backend part without using any framework like Angular or react.

I have 3 main file for my codes.

  1. index.html
  2. customer.js (for front end part)
  3. server.js (for backend part)

My backend part like below;

const express = require('express');
const app = express();
const axios = require('axios').default;

API_KEY = "***";
const PORT =3000;

// app.use("/static", express.static(__dirname + '/customer'));

app.get('/', (req, res) =>{
    axios
      .get(`http://api.openweathermap.org/data/2.5/forecast?q=amsterdam&appid=${API_KEY}`)
      .then(resp => {
         let weatherDetail = resp.data;
         console.log('a single country details: ', weatherDetail);
         res.send(weatherDetail);
      })
      .catch(err => console.log(err));
  });

app.listen(PORT, () => console.log(`My app listening on port ${PORT}! `));

When I write localhost:3000 on browser, I can see the weather api's data. However I want to see html file with functions in customer.js and api's data. Therefore I tried to write res.sendFile((__dirname + '/index.html')); inside app.get('/', (req, res)) function. However, in this situation I can see only html page without getting data from backend.

How can I call data getting from backend part in frontend part inside customer.js file?

My codes in customer.js like below (but I'm not sure if I use axios agan inside this file)

const apiCall = cityName => {
    let apiKey = "***";
    let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}&units=metric`
    axios
        .get(apiUrl)
        .then(getWeather)
        .catch(err => {
            console.log(err);
            err.response.status === 404 ? alert(`The country ${cityName} doesn't exist.`) : alert('Server error! Sorry.');
        });
};
apiCall(amsterdam)

    function getWeather (response) {
        let city = document.querySelector("#city");
        city.innerHTML = response.data.name;
.
.
.
.
}
Todd
  • 652
  • 2
  • 19
  • 37
CeydaU
  • 11
  • 1
  • 3
  • You are trying to send `weatherDetail` but there is no variable like this – b1617 Jun 29 '21 at 08:59
  • Yeah correct, I added to my code but I forgat to write here.. I wrote this -> let weatherDetail = resp.data; so there is a variable – CeydaU Jun 29 '21 at 09:18
  • You don't need axios in front end as their already browser apis you can utilize. Take a look at [MDN Ajax](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX) – Todd Jun 29 '21 at 21:50
  • posted a solution did it work? – Jatin Mehrotra Jun 30 '21 at 10:22

2 Answers2

1

I would recommend to use a templating engine like handlebars or ejs.There are tons of examples for it, and sending data from backend to frontend becomes a piece of cake when using any templating engine. my personal favourite is handlebars because of its simple syntax.

Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
0

It is advisable not to use document.querySelector if you're using Angular or React. React/Angular will have the browser repaint the DOM by making updates in the "root" div element of the index.html file whenever there is new data available to update. Also, why do you want to send a HTML file? You could have a route in Node like below

route.get('/weather', (req, res) => {
    // do your api call with axios to get weather data
   res.json(weatherData);
});

from your front-end you could make an API call to '/weather' route and consume the JSON data

axios.get('baseUrl/weather').then(res=>{
   console.log("weather data", res);
}).catch(...);

You could also fetch weather data directly from front-end like above.

dee
  • 2,244
  • 3
  • 13
  • 33
  • Hi there, thanks for your explanations but my lead wanted me use pure js instead of using framework in frontend side. Today, I solved it problem. – CeydaU Jun 30 '21 at 15:02
  • 1
    Glad you solved it. a few months back I had asked kind of a same question :) https://stackoverflow.com/questions/63353801/microfrontend-send-just-the-first-page-from-node-without-sharing-any-files-fold – dee Jun 30 '21 at 16:34