Getting express.js to show a public folder - javascript

I've recently built a quick one page app using express.js, and this is really my first js framework (actually, my first js project, so I'm really new to this). I've got a subscription to the new typography.com cloud fonts, and I'm having trouble locating the "fonts" folder that I place in the public folder. Is there a way I need to add the folder and specify a route?
Here's my app.js file:
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static('public'));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I haven't made any changes to the routes at all, so they are just default.

Please use express.static setting:
app.use(express.static(process.cwd() + '/public'));
And place your fonts folder in that public folder.

If you are using Heroku, you may want to look at this thread: Deploy Nodejs on Heroku fails serving static files located in subfolders
The guy explain that he struggled with "__dirname" until he specified the last version of NPM in his package.json:
"engines": {
"node": "0.10.11",
"npm": "1.2.25"
}
If that doesn't work, you might try:
// At the top of your web.js
process.env.PWD = process.cwd()
// Then
app.use(express.static(process.env.PWD + '/public'));
Instead of "__dirname"
Though, all that is probably useless if you already struggle localy.

Related

Angular 7 - Only "dist" folder is rendering on browser but not "src" folder with nodejs

Hi i am starting a project of nodejs app with angular7. This is my mail server.js file in nodejs
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var router = express.Router();
var app = express();
app.use(cookieParser());
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.set('view engine', 'pug');
app.set('views', __dirname + '/app/views');
app.use(express.static(__dirname + '/public'));
app.use('/', express.static(__dirname + '/angular/src'));
require('./app/routes')(router);
app.use(router);
app.listen(2233, function(){
console.log('app started on 2233');
});
This line app.use('/', express.static(__dirname + '/angular/src')); indicates that i want to render src folder inside angular folder on nodejs app load but this is rendering blank screen. When i run ng build and change it to app.use('/', express.static(__dirname + '/angular/dist')); then start working.
All the tutorial showing to run ng build and run angular inside node but why can i use src folder inside nodejs.
src folder is used during development. They are actual source files which has your programs in readable format.
dist is generated when you do ng build, it will have all your src files, assets and your node modules combined and minified into a small package.
So, there is no point of having src in your deployment
Updated:
When you are in development as you said for every small change minfying the code and building whole code again takes lot of time. So, when we do ng serve it will just convert files to js but no minification or other things will happen.
Why src will not work if you copy it for deployment is, src contains .ts files if you are using latest Angular and you have to transpile it to JS with some modifications required in order for it to be understandable by browser.

Failed to lookup view "index.ejs" in views directory

I have the following code in my express app (app.js file):
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
});
app.listen(8080);
And the following dependencies:
"ejs": "^2.6.1",
"express": "^4.16.3",
"request": "^2.87.0"
And this is my folder structure:
myapp
app.js
package.json
views
index.ejs
node_modules
[all node files]
But when I run the app, it shows this error:
Failed to lookup view "index.ejs" in views directory "mylocaldirectory/myapp/views"
If it would help here are the other error messages:
at Function.render (/mylocaldirectory/myapp/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/mylocaldirectory/myapp/node_modules/express/lib/response.js:1008:7)
at //mylocaldirectory/myapp/app.js:11:9
at Layer.handle [as handle_request] (/mylocaldirectory/myapp/node_modules/express/lib/router/layer.js:95:5)
at next (/mylocaldirectory/myapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/mylocaldirectory/myapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/mylocaldirectory/myapp/node_modules/express/lib/router/layer.js:95:5)
at /mylocaldirectory/myapp/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/mylocaldirectory/myapp/node_modules/express/lib/router/index.js:335:12)
at next (/mylocaldirectory/myapp/node_modules/express/lib/router/index.js:275:10)
I get no error if I just use res.send("SOME TEXT") but when I try to render an ejs file, it doesn't. What's the issue?
You need to set your view directory and your viewengine before requesting any of your view files.
Hence you need to add the below lines, before your app.get
app.set('views', './views');
app.set('view engine', 'ejs');
And your res.render('index.ejs'); should be changed as,
res.render('index');
Hope this helps!
First you have to tell express what view engine to use by setting
javascript
// set the view engine to ejs
app.set('view engine', 'ejs');
And when referring to a view you should leave out the extension. So instead of res.render('index.ejs'); use res.render('index');.
Setting up the view folder is not required since you're using the default view folder views to store your view files.
This issue basically comes when your ejs views engine unable to find file or folder.
So do following checks:
1.check directory name. it should be 'views' not 'view'.
2.check file under directory having correct file extension or not? it should be .ejs only not others like .html or .json etc.
3.tell express that i am going to use ejs view engine by using below code:
app.set('view engine','ejs');
Did you set up the views folder?
app.set('views', './views')
I used this:
const express = require("express");
const server = express();
const path = require("path");
server.set("views", path.join(__dirname, "views"));
server.set("view engine", "ejs");
server.use(express.static("public"));
server.get("/", (req, res) => {
res.render("index");
});
server.listen(8080);
make sure you have only css files in public folder .other folders can be outside the public folder.
try this it worked for me.
// view engine setup
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
In your case, 'app.set' function is unable to find 'views' folder.
So use following...
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs')
or you can do as following
const path = require('path')
//path is inbuilt module in nodejs, so don't need to install it.
app.set('views', path.join(__dirname, '/views'))
app.set('view engine', 'ejs')
both methods are same.
__dirname will concatenate absolute path to 'views' folder.
(note: Notice that . is should not be there while concatenating with absolute directory path.
So don't use './views' after __dirname, use '/views' only)
Make Sure you have corrected file name with ejs extension.
Make Sure you have corrected folder name views.
app.set('view engine', 'ejs')
It will work properly
app.set('views', './View'); //./View(You already created folder)
app.set('view engine', 'ejs');
res.render('index', { kindDay: day });
index is my EJS file.
kindDay is EJS file-created key.

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.

Node Js express serve website with project name

I created a simple node js application with Node and Express. It just used to serve couple of static files. It is serving files as
http://localhost:3000/index
http://localhost:3000/users
But I want to serve it with a project name. some thing like as follows
http://localhost:3000/myNodeProject/index
http://localhost:3000/myNodeProject/index
How do I do that ?
My Code
var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
//Routers or HTTP Rest Requests
app.use('/', routes);
app.use('/users', users);
var server = http.createServer(app);

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

Categories