Cannot link my page to the router in node.js - javascript

Can someone help me out? I am trying to connect my HTML page to the router, so that when I go to a certain link, I can render a certain HTML page. Right now, I am just trying to send something and nothing works. Here is a screenshot of my work:
My ultimate goal is to render movie_info.html.
Thanks in advance!

you don't have to render html pages. You can simply open html as static file.
var express = require('express');
var server = express(); // better instead
server.use('/', express.static(__dirname + '/your_html_page_folder'));
server.listen(3000);

You can also do this with ejs templates. first you have to install ejs
npm i ejs
then create a views folder in your main folder.In that folder save your file with .ejs extension.In your case movie_info.ejs
in movie_info.js do the following:
const express = require('express')
const app = express();
// setting ejs as templating engine
app.set('view engine', 'ejs');
app.get('/test', function(req, res, next) {
res.render('movie_info');
});
app.listen(3000)
this will render your page.

Related

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 to route HTML Node js Express js

I am trying to route multiple HTML pages. It loads index.html file, but when I want to load raw.html, it says
Error: Failed to lookup view "error" in views directory
app.js
var routes = require('./routes/index');
var users = require('./routes/users');
var raw = require('./routes/raw');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/raw', raw);
/routes/index.js
var express = require('express');
var router = express.Router();
var path = require('path');
router.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
module.exports = router;
/routes/raw.js
var express = require('express');
var router = express.Router();
var path = require('path');
router.get('/raw', function(req, res) {
res.sendFile(path.join(__dirname + '/public/raw.html'));
});
module.exports = router;
You are configuring express to use the pug (formerly known as jade) template engine.
A template engine enables you to use static template files in your
application. At runtime, the template engine replaces variables in a
template file with actual values, and transforms the template into an
HTML file sent to the client. This approach makes it easier to design
an HTML page.
The error you mention above is because you do not have a template file named error.pug in the views directory. The template engine catches the first error, which is:
Error: ENOENT: no such file or directory,
and then tries to render the error template.
res.sendFile(path.join(__dirname + '/public/index.html'));
The line above in your file routes/index.js will try to send routes/public/index.html and that file do not exists.
You can fix your express configuration using a correct path in your request handlers, i.e:
router.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/../public/index.html'));
});
You should also remove the template engine configuration, since you do not seem use it.
You mentioned in the comments that you want to use Angular, so...
You dont need a view engine if you want to use Angular.
When using Angular, the "main" part of your website is located on the clients' side, in the index.html file (this is not 100% correct, just an example).
That part (in the users browser) has JS code (Angular) that sends http request to the server - $http.
The server part basicaly just operates these requests and sends back data to Angular on the clients side, and then you do what ever you want with that data on the clients side.
You can respond to these requests with Node, PHP and etc.
This is similar to the idea behind AJAX, when only small parts of the page are changed without reloading the whole page.
On the other hand, if you are using view-engines, when the server gets a request, for example:
app.get('/',.routes.views.home);
The server renders an entire html page and sends it to the client, as it works with PHP.

Heroku not loading js script 404

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".

AnguarJS + node.js (web-server.js) remove hashtag from url and support it by server side

As far as i understand in order to remove the hashtag from angularJS i need to add the following code:
config(function($locationProvider) {
$locationProvider.html5Mode(true);
}).
after added this code, i get 404 from my simple server (web-server.js) which is the same simple server provided with angular tuotorial.
From the stackoverflow i found 2 links that helped me to understand that i need to add routing to my server in order to support this operation.
AngularJs Routing without hashtag in link?
routing and clean path (no hashtag) not working in angularJS
well i didn't understand how to add web-server.js the routing i needed
my link was previously was: /app/index.html/#cars
and now he is /app/index.html/car
how should i changed web-server.js in order to fit my new routing needs?
thanks.
The simlpiest and the fastest way to set up node server with routing is to use Express framework.
With Express very simple skeleton of your webapp would look like this:
var http = require('http');
var express = require('express');
var app = express();
app.configure(function() {
app.set('views', __dirname + '/app');
app.set('view engine', 'ejs'); //EJS template engine (no HTML for now)
app.use('/public', express.static(__dirname + '/public')); //specify path to your static files
});
//"car", "bus", and "van" are the pages of your app
app.get('/:page(|car|bus|van)', function(req, res) {
res.render('index', {
page: req.params.page //pass page to the view (just in case)
});
});
http.createServer(app).listen(80);
Then you will have to create /app/index.ejs file which is in fact the html file with some additioal features.
Thus, when you navigate in your browser to /car, /bus, or /van you will see the content of index.ejs file.
Hope this helps!
Edit
I've just corrected /:page(|car|bus|van) part. Please try the last version
Edit 2
Oh, I forgot to say, you have to npm install ejs from command line to start using EJS templates

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.

Categories