i have an issue on my code (Weather App using OpenWeahterMap Api) after i tried to move my apiKey and apiUrl to the .env file, i already got this error in the terminal and it's not clear why its happend
here is my code :
const express = require("express");
const https = require("https");
const { restart } = require("nodemon");
const bodyParser = require("body-parser");
const dotenv = require('dotenv');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use('/css', express.static(__dirname '/node_modules/bootstrap/dist/css'));
// The app will redirect to index.html page
app.get("/", function(req, res){
res.sendFile(__dirname "/index.html");
})
app.post("/", function(req, res) {
dotenv.config({ path: '/.env' });
require('dotenv').config();
const weatherUrl = process.env.API_URL;
const apiKey = process.env.API_KEY;
const city = req.body.cityName;
const unit = "metric";
const url = weatherUrl city "&appid=" apiKey "&units=" unit
// the response will recive the data and will parse the jsonData from the API
// and will print the the current temprerature description weather icon
https.get(url, function(response){
response.on("data", function(data){
const weatherData = JSON.parse((data));
const temp = weatherData.main.temp;
const weatherDescription = weatherData.weather[0].description;
const weatherIcon = weatherData.weather[0].icon;
const imageUrl = "http://openweathermap.org/img/wn/" weatherIcon "@2x.png"
res.write("<p>The Weather is currently " weatherDescription "</p>");
res.write("<h1>The temprerature in" city "now is " temp " degress Celcius.</h1>");
res.write("<img src=" imageUrl ">");
res.send();
})
})
})
// default port can be change
app.listen(3333, function() {
console.log("Server is running on port 3333");
});
the error message :
Server is running on port 3333
/Programming/JS/WeatherApp/app.js:35
const temp = weatherData.main.temp;
^
TypeError: Cannot read property 'temp' of undefined
i am not sure where is exactly the problem because it's first time i am using Express JS
CodePudding user response:
You need to identify where your path is for your .env file if it is in the same directory as this file then you need to put ./.env
if it is in a directory above this one you need to put ../.env
or two directories ../../.env.
/.env
doesn't mean anything
The .env file should also not have semi colons to delimit the end of your keys.