how to call URL from local env in Express JS - javascript

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

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.

Related

Why is the server response incorrect when the request is read correctly?

I'm on the Node.js repl, I created a new project folder and initialized the NPM, then I installed the Express package and wrote the following code into the js file:
const express = require('express');
const app = express();
app.listen(5000, function(){
console.log("server started on port 5000");
})
app.get("/", function(req, res){
res.send("Hi There! Welcome!")
})
app.get("/speak/:animalName", function(req,res){
var animalName = req.params.animalName;
var verso = "verso";
if (animalName = "pig"){
verso = "oink"
} else if (animalName = "dog"){
verso = "bau"
} else if (animalName = "cat"){
verso = "Miao"
}
console.log(req.params);
res.send("THE " + animalName + " says " + verso);
})
app.get("*", function (req, res){
res.send("Sorry, the page cannot be found")
})
When I open the js file with Nodemon the server starts correctly and when I type a specific pattern in the URL field the console.log returns me the req.params correctly (in the example below: for I typed "cat" the console returned { animalName: 'cat' }
Nonetheless, the response in the browser is not the correct one:
You're using a single = in your conditions. This always assigns the variable, instead of testing for equality. Use == or ===.

Accessing a functions from a js file thats in a public directory

I have a JS file in a folder called public, which also has my CSS file in it. I'm trying to access a function from the JS file (scripts.js), but am having no luck. I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js'. If anyone can help me out, that would be great.
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get('/', function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
var temperature = scripts.converter(data.currently.temperature)
res.render("results", {data: data, temperature: temperature})
} else {
console.log(response.body);
}
});
});
app.get('/results', function(req, res){
res.render("results");
});
app.listen(3000, function(){
console.log("Server has started");
})
scripts.js
module.converter = function(cel) {
var cel = (far - 32) * (5/9);
return cel;
}
exports.data = module;
The path to your module is wrong.
Try var scripts = require("./public/scripts.js"); instead.
You are loading /scripts.js, which is a scripts.js file located at your computers root. To load a file in the current directory, you would do ./scripts.js. In a directory above the current one, it would be ../scripts.js.
If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. directoryname being public in your case

nodeJS: Sending html data from one js to another

The code below is working
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB')
app.use('addUserToDB', addUserToDB)
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
However, when I try to remove the following method and place it into another .js file so I can get the firstName from that file. It's not working. The following code is in addUserToDB.js:
var addUserToDB = app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = addUserToDB;
I have tried making a addUserToDB.js file and added the code
var express = require('express')
var app = express();
app.get('addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
but it seems I am missing something because it doesn't work. Thanks.
A few things here. First, need to do a require of addUserToDB.js from server.js (I will assume that's the name of your main file) and then use it as a middleware. Also, you need to export the app from addUserToDB.js.
server.js:
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB');
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.use(addUserToDB);
addUserToDB.js:
var express = require('express')
var router = express.Router();
router.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = router;

Use local files in my node.js/socket.io project

I have a node.js/socket.io project. I'm using Bootstrap in my pages and I display images dynamically on my pages. The problem is that I can't use the images and the Bootstrap files. Node.js/socket.io doesn't recognize the links... I have solved the Bootstrap problem by uploading all Bootstrap files on a distant server and it works! But I can't use local files like my images.
How can I "load" an image folder which I can use the images from it?
Here is my server.js :
var http = require('http').createServer(createServer);
var fs = require('fs');
var url = require('url');
var nStatic = require('node-static');
var express = require('express');
var app = express();
function createServer(req, res) {
var path = url.parse(req.url).pathname;
var fsCallback = function(error, data) {
if(error) throw error;
res.writeHead(200);
res.write(data);
res.end();
}
switch(path) {
case '/galerie.php':
doc = fs.readFile(__dirname + '/galerie.php', fsCallback);
break;
default:
doc = fs.readFile(__dirname + '/index.php', fsCallback);
break;
}
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
http.listen(8080);
This works :
<script src="http://website.ch/LivreOr/js/download.js"></script>
But this doesn't work :
<img src="../LivreOr/img/img.png">
I have solved my problem. Here is what I have changed :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/galerie', function(req, res) {
res.sendFile(__dirname + '/galerie.html');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
//var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
server.listen(8080);

Node.js- Make array in app.js available in a module

In my Node app.js, I don't necessary need to have my array openConnections global...but I want it in app.js and accessible by module sse_server.js for the sseStart function. How can I do this?
app.js:
var express = require('express');
var morgan = require('morgan');
var fs = require("fs");
var createDomain = require("domain").create;
var app = express();
app.use(express.static(__dirname + '/app/static/views'));
app.use(express.static(__dirname + '/app/static'));
app.use(express.static(__dirname + '/app/images'));
app.use(express.static(__dirname + '/app'));
var openConnections = [];
var sseStart = require(__dirname + '/app/scripts/sse_server.js');
app.get('/subscribe', sseStart);
var callAllApiAndSave = require('./app/scripts/api_scripts/call_all_api.js');
var db = require(__dirname + '/app/data/db.js');
var mainDomain = new createDomain();
mainDomain.run(function () {
mainDomain.on('error', function() {
console.log('yoyoyoyoyoyoyoyoyoyoyoyoyoyoyo');
});
mainDomain.on('error', function(er) {
console.log('error, but oh well', er.message);
});
db.connectDatabase();
setInterval(callAllApiAndSave, 120000);
var server = app.listen(9000, function() {
console.log('Listening on port %d', server.address().port);
});
});
sse_start.js:
function sseStart(req, res) {
console.log(req);
// set timeout as high as possible
req.socket.setTimeout(Infinity);
// send headers for event-stream connection
// see spec for more information
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
// push this res object to our global variable
console.log("Creating SSE connection for " + req.connection.remoteAddress);
openConnections.push(res);
console.log("Total current live connections: " +
openConnections.length);
// When the request is closed, e.g. the browser window
// is closed. We search through the open connections
// array and remove this connection.
req.on("close", function() {
console.log("Closing SSE connection for "
+ req.connection.remoteAddress);
openConnections = openConnections.filter(function(storedRes) {
if (storedRes !== res) {
return storedRes;
}
});
if (!openConnections) openConnections = [];
console.log("Total current live connections: " +
openConnections.length);
});
}
module.exports = sseStart;
Looking at the code you posted openConnections is only used in sse_start.js so why not put it there?
If you really want to share that array between those two files you can just put it in a separate module and require it in app.js and sse_start.js.

Categories