How to load an external js file from another server? - javascript

I have the following express code for get method:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
app.listen(3000);
I want this code snippet to do:
load a js file from a different server
embed this js file inside the index.html file that was brought by the get request.

You want to fetch the distant js file with an http request : see the doc.
Then, you want to use a template engine to insert the content of the file into index.html (which has to be ready to be templated), see express doc about template engines.

Related

Using dotenv for API keys in multiple JS files

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

Cannot GET /blah.html - .ejs can't load html?

I'm using Nodejs and Express to create a dynamic webpage.
I have a home.ejs file that has this iframe:
<iframe id="newstable" src="/news_tables/2018-08-04.html" height="1000" width="100%"></iframe>
My folder directory is:
News_Aggregator (includes app.js)
News_Aggregator/news_tables (includes a bunch of html files, e.g. `2018-08-04.html`)
News_Aggregator/views (includes my `home.ejs` file)
And my app.js:
const express = require('express');
const app = express();
app.set("view engine", "ejs");
app.get('/', function(req, res){
res.render('home.ejs');
});
app.listen(8000, () => {
console.log('Example app listening on port 8000!')
});
However, when home.ejs is rendered, my iframe doesn't load the html page:
This works in "normal" HTML. What am I missing to get the .ejs file to find this and render correctly?
You get the error because the server dosen't know where to get the files from.
First You must define where the static .ejs files will be. Lets say something like this. if your files are in a public folder(ejs,css etc) and you will get them from there. Setup both with:
app.use(express.static(__dirname + '/public'))
app.set('views', path.join(__dirname, '/public'));
from here you can just in your response if you have a home.ejs file
res.render('home', {});
You should look over Express static() from here and learn how to serve files
The fact your HTML is generated from a .ejs file is irrelevant.
Your HTML says the browser should ask the server for the URL /news_tables/2018-08-04.html.
Your HTTP server has a route app.get('/', and no other routes.
Your HTTP server doesn't know about the URL /news_tables/2018-08-04.html, so it returns a 404 Not Found.
You need to write code which will serve up all the URLs you want it to.
You should probably look at the Express static() middleware if you want to serve static files.
The only thing that works is removing ".html" from address "localhost:3000/index.html".

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (i.e., if I hit "http://localhost:3000/" in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using
<script src="/myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="./myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>
it doesn't work. The myJavaScriptFile.js file is never reached.
My express app looks like this:
var express = require('express')
var testMethod = require('./test')
var app = express()
app.use(bodyParser.urlencoded({ extended:false }));
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
app.get('/', function (req, res) {
console.log('In /');
res.sendFile(__dirname + '/index.html');
})
Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).
Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.
Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:
app.use(express.static('public'));
Now, you will be able to load the files under the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
More Detail Here
Happy Helping!

Directory-Dynamic Node.JS express server

I am new with the whole web-server side of Node.JS,
Unfortunately I cannot find how to make my express server serve dynamic web pages.
I understand routes, and how they work.
Here's my code
var express = require('express');
var app = express();
app.get('/', function (req, res){
res.send('Hello There From Express!\n');
});
app.listen('200');
This will only server the / directory, everything else will fail.
How would i set this up where it will serve a dynamic webpage range,
So like if the user wanted to type in http://example.com/billing.html,
it would redirect to the billing.html file.
I don't want to have to put in a routing line for each page, I would like to be able to just dynamically serve webpages..
Sorry if i'm not making any sense, i'm not the best at asking questions.
If you are wanting to just have express serve a folder of static HTML files without dealing with each one individually, you could define your app as:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/html')); //where /html is a subfolder of your app
app.listen('200');
with /html containing all of your static files.

Error when rendering HTML in express

I'm trying out a simple one page render and I'm obviously doing it wrong:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.render('home.html');
});
app.listen(3000);
console.log('Listening on port 3000');
Error:
Error: Cannot find module 'html'
I want to load a page with CSS/images and wanted to know where to store the CSS/images/scripts/HTML and how to load it. I have yet to find many example express apps.
When using res.render, you are rendering a defined view. The documentation state:
Render a view with a callback responding with the rendered string.
When an error occurs next(err) is invoked internally.
For specific HTML, you either have to load the file with fs.readFile, or have Express use a rendering engine, such as Jade or EJS. For example, this code sample would apply the EJS render engine to all files with the extension .html.
app.engine('html', require('ejs').renderFile);
Then you can render a file like this. This is an example of passing variables to the HTML file, because that's what embedded JavaScript is used for.
app.get('/', function (req, res) {
res.render('/file', {
pass: 'arguments',
to: 'the file here'
});
});
That is more convenient than having to read the file on each load like so:
app.get('/', function (req, res) {
fs.readFile('/index.html', 'utf8', function (err, data) {
res.send(data);
});
});
Although this is aside from your question, this is how passing variables to EJS works. It even works with if statements and loops, since it accepts all JavaScript. Putting console.log in the file would log each time the file was rendered.
<span><%= pass %></span>
<!-- after rendering -->
<span>arguments</span>
If you need to serve other resources, such as CSS, JavaScript, or other html files, you could use Express' directory function.
app.use(express.static('/'));
Then you wouldn't need to render your HTML at all. It would be statically served.
I want to load a html with css/images and wanted to know what is the layout of where to store the css/img/js and the html and load it? I am yet to find many example express js apps.
Assuming that you have installed express, within your express project you will find public folder. within public folder you will find three folder - images, javascripts, and stylesheets . As the names suggest place your css/img/js in their respective folders.
You place static HTML files not using any templates in the in the express project public folder and invoke it using:
app.get('/', function(req, res) {
res.redirect('/home.html');
});

Categories