Using dotenv for API keys in multiple JS files - javascript

I am new to web programming but not programming in general. I use node.js to create a website and am using dotenv to hide API info form github and am having some trouble understanding something.
My .env file is in the root directory and contains:
GOOGLE_CALENDAR_API_KEY=key_value
I use an app.js file to set up and run my server and send the index.html file.
//jshint esversion:6
const https = require('https');
const bodyParser = require("body-parser");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.listen(5000, function(req, res) {
console.log("Listening on port 5000.");
});
Then I have another script file I use named "custom.js" to run the bulk of my webapp. Inside, I try to use process.env to get the API key.
window.onload = function()
{
const googleAPIkey = process.env.GOOGLE_CALEDAR_API_KEY;
.
.
.
but I get an error "Uncaught ReferenceError: process is not defined"
I have also tried moving the require("dotenv").config() line to the custom.js file and that fails. There is something I am doing wrong with trying to access information from one file into another, but I don't understand what.
Any help would be appreciated!

From what's i understood you trying to access the process variable of node.js app from the client browser and it is not possible. The process variable is only accessible in the scope of the node.js application and not in the browser where you run your client.

you have to add require("dotenv").config(); on second script file also

It looks like you are trying to access the Process variable on the client-side / frontend. You cannot access those variables from a client browser or machine

Related

Static files not showing on express server

I am currently trying to get my JS express server to display my static HTML files using this code.
My JS Express code
**When I run my server I get this error message Error: ENOENT: no such file or directory, stat: and the directory path to the file. the directory path exists so I don't understand why it wont show the file and its contents. could someone explain this to me please. **
What I have tried in addition to my written code.
**I have tried changing the location of my project entirely and that didn't work.
I have tried using app.use, __Fileneme instead of __dirname, rewriting the code nothing works.
Im using Node. js I have express installed and required I have rewritten the code several times to be sure the error was not syntax error "although VS code would have made me aware of any syntax errors" I just at a loss now. this is a simple server that should display my html files just fine yet nothing I do works.**
try adding this line at the top:
// where /public is the folder where 'welcome.html' is
app.use('/public', express.static(__dirname+'/../public'));
the npm path package may be helpful as well
app.get('/Home', (req, res) => {
console.log(path.join(__dirname ,'/public/welcome.html'));
res.sendFile(path.join(__dirname ,'/public/welcome.html'));
})
const express = require('express');
const app = express();
app.use(express.static('public',{
extensions: ['html', 'htm']
}));
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});

Why express api doesn't GET this folder?

I have a js script for a server is required to GET files from folder called "public". But when I go to localhost it says Cannot GET / .The script is:
const express = require('express');
const app = express();
app.use('/', express.static('/public'));
app.listen(3000);
I am really new to js, express api, and web dev in general so could anybody help me?
I can't add a comment since I don't have the rep, but judging by your other comments you want to change the /public to ./public

Issues with linking Javascript files with Node.js and HTML

I am making an application with node.js and I basically want render a canvas with node.js so I can access a json file on the server since you can't change client storage on browsers. To add on when running my files I get this weird syntax error.
Uncaught SyntaxError: Unexpected token '<'
Further examination shows that my javascript files that I am requiring (see internals folder) are being overwritten with html, thus causing the error. My question is why is it overwritting only the files I am requiring from the html I am rendering? To add on I am running on a dynamic port (65535) and on a localhost (client). My code is here
Your node server is not serving your static files, it only serves one html.
You might need to set up a static file server like or programm you server to lookup GET /internals/render.js and scaleCanvas.js
You can use express for that, it has all this out of the box.
https://expressjs.com/en/starter/static-files.html
var app, server,
express = require('express'),
path = require('path'),
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000,
root = path.resolve(__dirname, '..');
app = express()
app.use(express.static(root + '/public'));
server = app.listen(port, host, serverStarted);
function serverStarted () {
console.log('Server started', host, port);
console.log('Root directory', root);
console.log('Press Ctrl+C to exit...\n');
}
This is because you are sending the index.html file for all requests in your app.js file, ignoring the request URL.
You need to properly serve the JS files. You can take a look here for more details: https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

Node.js socket.io.js not found or io not defined

I'm trying to run a node.js application on my freebsd server, but I can't get the socket.io library to work with it. I've tried including:
<script src="/socket.io/socket.io.js"></script>
Which gives a 404 error, and if i link directly to the file (i.e. where it is in my public_html folder) I get the io not defined error.
Thanks in advance
Try creating another node.js application that has this single line in it and then run it with node.js
var io = require('socket.io').listen(8000);
Then in your browser visit http://127.0.0.1:8000 and you should get the friendly "Welcome to socket.io." greeting. If you are getting this then socket.io is running and will serve the socket.io.js file.
The only other thing that I can think of that might be happening is that you might not be linking to the alternate port in your client file. Unless you're running the socket.io server on express which is running on port 80. For now create a client file that has the script source for socket.io set to
<script src="http://127.0.0.1:8000/socket.io/socket.io.js"> </script>
This should connect to the socket.io server running on port 8000 and get the socket.io.js file.
Your node.js application still has to serve it - it does not get served automagically. What do you have in your server? It should be something like
var app = require('express').createServer();
var io = require('socket.io').listen(app);
or similar (the listen is important). The location is not a real location on the disk - socket.io library should intercept the URL and serve its clientside library, as far as I understand.
Add the following after body parser:
, express.static(__dirname + "/public")
So something like:
var app = module.exports = express.createServer(
express.bodyParser()
, express.static(__dirname + "/public")
);
For those who got the same kind of issue if they run (open) your html file directly from your local file directory(ex: file:///C:/Users/index.html).
Solution: You have to run(open) the file through localhost (ex: http://localhost:3000/index.html) where the server is listening to.
Below code snippet shows how to create a server and how to wire together with the express and socket.io
const express = require("express");
const app = express();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
///////////////////////////////////////////////////////////////
// Any other server-side code goes here //
//////////////////////////////////////////////////////////////
httpServer.listen(3000, () => {
console.log(`Server listening to port 3000`);
});

Categories