Express .JS / Node.JS Причудливый сервер приложений погоды - PullRequest
0 голосов
/ 15 апреля 2020

Мое приложение работает, но при первом запуске оно не обновляет интерфейс.

Вызов fecth ("/ all") не возвращает никаких данных, но предполагается, что и локальный сервер, похоже, возвращает пустой объект, но его следует обновить, чтобы иметь последние данные.

Однако, когда вы вводите новый город, пользовательский интерфейс обновляется данными первого города, и каждый раз кажется, что он отстает. Я провел исследование и застрял на данный момент.

Код на стороне клиента:

/* Global Variables */

// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth() + "." + d.getDate() + "." + d.getFullYear();

const apiKey = `&APPID=4f2ae032089f5dece0abe5982bc51612`;
const baseUrl = `https://api.openweathermap.org/data/2.5/weather?q=`;

//MAKES async fetch request to openweather api
const retrieveData = async (url = "") => {
  const request = await fetch(url);
  try {
    let cityData = await request.json();
    return cityData;
  } catch (error) {
    console.log("opps: There is an error ", error);
  }
};

document.getElementById("generate").addEventListener("click", sendRequest);

//offcial request sent on click of generate button
function sendRequest(e) {
  const newCity = document.getElementById("zip").value;
  let mood = document.getElementById("feelings").value;

  newCity == "" || mood == ""
    ? alert(`Please fill in all fields`)
    : retrieveData(baseUrl + newCity + apiKey)
        .then(function (data) {
          postData("/data", {
            Temprature: data.main.temp,
            Date: newDate,
            mood,
          });
        })
        .then(function () {
          updateUi();
        });
}

let postData = async (url = "", data = {}) => {
  const response = await fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  try {
    const newData = await response.json();

    return newData;
  } catch (error) {
    console.log(`OOPSIE: ${error}`);
  }
};

const updateUi = async () => {
  const request = await fetch("/all");
  try {
    const allData = await request.json();
    console.log(allData);

    document.getElementById("date").innerHTML = allData.date;
    document.getElementById("temp").innerHTML = allData.temp;
    document.getElementById("content").innerHTML = allData.mood;
  } catch (error) {
    console.log(`OOPSIE: ${error}`);
  }
};

И Код на стороне сервера: (Express. js)

// Setup empty JS object to act as endpoint for all routes
let projectData = {};

// Require Express to run server and routes
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
// Start up an instance of app
const app = express();

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors());

// Initialize the main project folder
app.use(express.static("website"));

// Setup Server - use dynamic port if set else 5000
let port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server up and Running on Port: ${port}`);
});

app.post("/data", cityWeather);

function cityWeather(req, res) {
  projectData = {
    temp: req.body.Temprature,
    date: req.body.Date,
    mood: req.body.mood,
  };
  res.send(projectData);
  return projectData;
}

app.get("/all", getData);

function getData(req, res) {
  res.send(projectData);
}

Я предположил, что, поскольку функция updatUi() вызывается последней, она сможет получить доступ к объекту projectData, когда все будет обновлено. Но даже console.log allData в коде на стороне клиента ничего не дает при первом запуске.

Заранее благодарю всех

...