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".
Related
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.
I have a node server file, app.js which uses express.
The file looks like this
var express = require('express')
var app = express();
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
If I run $ node app.js from my terminal it launches and if I navigate to localhost:3000 on my machine I see Hello World!.
I have uploaded the file to a server and try and navigate to the index.html file , which is in the public folder, however it doesn't work.
Maybe I am missing many steps, but can anyone advise how I can launch the node app on my server?
Your server doesn't send index.html anywhere. It only serves "/" path by sending text "Hello World!".
With Node.js, you have to tell which content you want to send for each route.
You can simply send the specific file : (sure, but dirty)
app.get('/index.html', function (req, res) {
res.send(PATH_TO_FILE/index.html);
});
Or specify which path to use to serve files by default :
app.use(express.static(__dirname + '/public'));
And you put all your public files to serve automatically in the public folder :
YOUR_PROJECT/public/AUTOMATICALLY_SERVED_FILES
Where AUTOMATICALLY_SERVED_FILES can be index.html or css/style.css for exemple.
NB : NGINX is not useful at this point.
On the server, nodejs is configured right?
I use forever with nodejs, it is useful if you would like to use nodejs like a service on linux base system.
I am trying to build my first web app using MEAN on Heroku. I followed their guide to getting a sample app running. Then I downloaded the sample app code and altered it to load the login page. Unfortunately, I can't get the my app.js file to load. This is the angular script. In the main directory I have index.js that is running express. Anyways, I am able to get the .ejs .css and img files to load but this script wont. I am stuck. I need to be able to get past this to tinker enough to start learning the stack.
Script is in the public directory with the other files that get loaded. Code looks okay? Don't know why I get 404 on the script.
Any help is much appreciated!
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('pages/index');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
<script src="/js/app.js"></script>
Turns out changes weren't being pushed to the server. That's all folks!
You just need to move app.js to the public folder. This line app.use(express.static(__dirname + '/public')); in your index.js tells express to serve static assets out of the /public folder. Everything else in your project will be "hidden" on the server unless you expose it.
You could create a js folder in public and move app.js there. Then change the reference in index.ejs from src="/app.js" to src="/js/app.js".
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!
I have the following code:
var express = require('express');
var app = express();
var server = require('http').Server(app);
app.get('/', function(req,res){
res.sendfile(__dirname + '/index.html');
});
server.listen(3000);
However, only my index.html page displays, and I have a GET error for my other files. When I load index.html at localhost:3000, I have errors in the console with trying to find my main.js and app.css files. Even when I include my other files as a src in the html file, they are not able to load. I think this may be because I am only sending the single html file to the server. How can I handle this so that all of the relevant files are sent to the server?
Using
res.sendfile(__dirname + '/index.html');
in response to a get request won't serve up all your static files, only the individual index.html file — meaning your css and javascript files will not be found by your server (even when you link to them in your html).
You need to use the included express static middleware (the only included middleware in express v4).
If your static files are in the same directory as your server.js file then add
app.use(express.static('.'));
This serves up all of your local static files and makes them accessible on your server.
I wrote a blog post on this a while back:
https://medium.com/#willsentance/how-to-avoid-main-js-style-css-not-found-or-how-i-learned-to-love-serving-static-files-with-node-2121255da0fd
You haven't offered a route to the linked files.
Use the static middle-ware: http://expressjs.com/api.html#express.static
From the docs:
Following are some examples of using the express.static middleware in an Express app.
Serve static content for the app from the "public" directory in the application directory.
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
Disable logging for static content requests by loading the logger middleware after the static middleware.
app.use(express.static(__dirname + '/public'));
app.use(logger());
Serve static files from multiple directories, but give precedence to "./public" over the others.
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));