Hi I having some trouble with two functions in my code. I'm basically building a web app that uses express server, node, webpack and body-parser,cors as middleware. I need to fetch three data values from 3 apis. Right now I can get one of them but the other two namely weather data and picture data are causing issues. The project structure is as follows:
My index.js file:
// Setup empty JS object to act as endpoint for all routes
let cityData = {};
let weatherData = {};
let picturesData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
// 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(path.resolve(__dirname "../../dist")));
// app.get("/", (req, res) => {
// res.sendFile('index.html', { root: 'dist' })
// })
app.get("/all", function sendData(req, res) {
res.send(cityData);
})
app.get("/allWeather", function sendWeather(req, res) {
res.send(weatherData);
})
app.get("/allPictures", function sendPictures(req, res) {
res.send(picturesData);
})
app.post("/addWeather", (req, res) => {
weatherData['temp'] = req.body.temp;
weatherData['datetime'] = req.body.datetime;
res.send(weatherData);
})
app.post("/addPicture", (req, res) => {
picturesData['pic'] = req.body.pic;
res.send(picturesData);
})
module.exports = app;
server.js:
const app = require('./index');
// Setup Server
app.listen(3000, () => {
console.log("App listening on port 3000")
console.log("Go to http://localhost:3000")
})
Now the functions related to the post request routes in index.js called "/addWeather" and "/addPicture" are in the client/js folder
the picture functions:
const receivePictureData = async () => {
const request = await fetch("/allPictures");
try {
const allData = await request.json()
const node = document.createElement("img");
node.setAttribute("id", "city-pic");
node.setAttribute("src", `${allData['pic']}`);
node.setAttribute("alt", "Your city");
document.getElementById("img-container").appendChild(node);
}
catch (error) {
console.log("error", error)
}
}
const postPictureData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
pic: data.pic
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
const updatePictureText = async () => {
const city = await document.getElementById("city").value;
const imgText = document.getElementById("img-text");
const cityData = await getCity(geoURL, city, geoUsername)
imgText.innerHTML = `Somewhere in ${cityData['geonames'][0]['name']}, ${cityData['geonames'][0]['countryName']}`;
}
the weather functions:
const getWeather = async () => {
const cityData = await getCity()
const res = await fetch(`${weatherURL}&lat=${cityData['geonames'][0]['lat']}&lon=${cityData['geonames'][0]['lng']}&key=${weatherKey}`);
try {
const weatherData = await res.json();
return weatherData;
}
catch (error) {
console.log("error", error);
}
}
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
const receiveWeatherData = async (i) => {
const request = await fetch("/allWeather");
try {
const allData = await request.json();
const node = document.createElement("li");
node.setAttribute("id", `entry-${i 1}`);
node.innerHTML = `<b>DATE:</b> ${allData['datetime']} <b>TEMPERATURE:</b> ${allData['temp']}`;
document.getElementById("entries").appendChild(node);
}
catch (error) {
console.log("error", error)
}
}
The issue is with the postWeatherData and postPictureData.
I tested the postWeatherData and postPictureData by console.logging the "response". It gave 404 not found. And the console gives these errors as well:
I don't know what to do as the next step in debugging... maybe change the post functions or change the routing in the server files... I really have no idea as I'm quite new to this stuff.
CodePudding user response:
if you want postWeatherData to be a route in express, you have to add it to index.js.
app.post("/postWeatherData", (req, res) => {
…
res.send(result);
})
CodePudding user response:
Well I was able to solve the issue by placing all the js files and index.html in the same root folder and linking them properly. But the project requirement is to use the project structure as given in the screenshot. I don't know what to do to solve this.