0

i am trying to send data from app.js to the server.js when generate is clicked .. the data come from an api successfully and console logged and saved to and object successfully and console logged successfully too , but when i try to send it to the server side its received an empty object .

my app.js code

// Personal API Key for OpenWeatherMap API
let baseurl = "http://api.openweathermap.org/data/2.5/weather?zip=";
let apikey = "MY API KEY";
let user_zip;
/* Function to GET Web API Data*/
let dataToSend = {};
getweather = async () => {
  user_zip = document.querySelector("#zip").value;
  user_input = document.querySelector("#feelings").value;
  if (user_zip == "") {
    alert("Sorry My App Cant Send Empty Request to the API ");
  } else {
    let res = await fetch(baseurl + user_zip + apikey);
    try {
      var data = await res.json();
      var temp = Math.floor(data.main.temp - 273.15);
      var date = new Date();
      dataToSend.date = date;
      dataToSend.temp = temp;
      dataToSend.feels = user_input;
      console.log(data);
      console.log(dataToSend);
    } catch (error) {
      console.log("error", error);
    }
  }
};
/* Function to POST data */
let postdata = async (url = "", data = {}) => {
  let request = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(dataToSend),
  });
};
// Event listener to add function to existing HTML DOM element
let clicking = document.getElementById("generate");
clicking.addEventListener("click", (event) => {
  getweather();
  postdata("/all", dataToSend);
});

   

and my server.js code

/* Empty JS object to act as endpoint for all routes */
projectData = [];
/* Express to run server and routes */
const express = require("express");
/* Start up an instance of app */
const app = express();
/* Dependencies */
const bodyParser = require("body-parser");
/* Middleware*/
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
app.use(bodyParser.json());
const cors = require("cors");
const { request } = require("http");
app.use(cors());
/* Initialize the main project folder*/
app.use(express.static("website"));
app.use(
  express.json({
    limit: "1mb",
  })
);
const port = 3000;
/* Spin up the server*/
const server = app.listen(port, listening);
function listening() {
  // console.log(server);
  console.log(`running on localhost: ${port}`);
}
// Callback function to complete GET '/all'
app.post("/all", (req, response) => {
  projectData.push(req.body);
  console.log(projectData);
});
// Post Route

some returns server returns empty object

but i got the data saved !!

Reyno
  • 6,119
  • 18
  • 27

0 Answers0