I'm trying to access a static 'home.html' file from the public folder. The architecture of the app is:
public
home.html
routes
index.js
views
myapp.js
myapp.js:
var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
index.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/about', function(req, res, next){
res.sendFile(__dirname + '/home.html');
});
module.exports = router;
The main problem I'm having is I'm unable to load the home.html file at '/about'. The "__dirname" in index.js is pointing to the routes folder, and I've tried concatenating '/../' to move up a directory, but I just get a 403 Forbidden Error. I suppose I could put the home.html file in the routes directory, but I really want to figure out how to solve the underlying problem. Of course, rendering the jade file from the views folder at '/' works perfectly fine. Thank you in advance for your help and expertise.
You are trying to use it in the wrong way. The reason that you get the forbidden error is that the clients shouldn't be able to access folders outside the static folder that you have selected.
What you can do is to select multiple static directories, like Setting up two different static directories in node.js Express framework
Though I recommend that you just place all your publically available files in the same directory.
Related
We built a web app using node, express and ejs. We want to deploy to CPanel. We copied the folders and the pages are not rendering. Do we need to change the routes to reflect the new folder structures and/or install node and all dependencies in the CPanel server? I did move things around and play with the routes a bit without much success. On my localhost I can see it perfectly, but once up it does not work.
So far my index.ejs is this:
<head>
<meta charset="UTF-8">
<title>Test de Zülliger</title>
<link rel="stylesheet" href="styles/style.css">
<link rel="shortcut icon" href="images/favicon.png">
</head>
the app.js is this:
const express = require('express');
const path = require('path');
const methodOverride = require('method-override');
const app = express();
const ejsMate = require('ejs-mate');
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }))
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', (req, res) => {
res.render('index')
});
app.get('/localizaciones', (req, res) => {
res.render('localizaciones/map')
});
app.get('/drawingpad', (req, res) => {
res.render('drawingpad/drawing-pad')
});
app.get('/finalizar', (req, res) => {
res.render('finalizar/finalizar')
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
});
my folder structure:
I did put index.ejs inside views and didn't make any difference, the CSS does not render and when on browser manually writing map.ejs it appears all the code, no render at all.
Deploying statically by just copying the files will only work for a static app, e.g. the build folder of a React application.
Node.js has to be installed and the server started in order for your application to work. This tutorial should help you when doing this in cpanel.
I am not sure how CPanel works, but for my knowledge (i do use MERN stack) you need all the code in one file. Therefore you need yarn run build or npm run build, which will make a build folder. Afterwards you upload just that folder and specify it in your hoster
I am totally new to Expressjs (Nodejs) and I am using "Express application generator" here is a link. I am building simple website and using (Embedded JavaScript templating / EJS) and I want to add webpack to my app.
Here is my project structure.
Here is my app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set path for static assets
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('404 page.');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.render('error', {status:err.status, message:err.message});
});
module.exports = app;
Does anyone have an idea how to do it, some example or anything that would help me?
Thanks everyone
Webpack is for single page application. There is only one index.html as the
hook, all the front-end contents will be generated by js files and bundled together by webpack then attached to the html hook.
If you use ejs or other template engine, you don't need webpack bundling your scripts, since you can split and load the scripts in your ejs files.
And your app.js and other Express things are backend things which run on your server, they don't need to be bundled or manipulated at all, you can do whatever you want, since those are on your server not users' browsers.
so just start to code your application.
EDIT ------------
so I figured out the issue, restarting and reloading nginx didn't have any effect, but if I stoped the nginx instance, then restarted it, any changes I made to the server files took effect. It's great that I figured it out, but could anyone give me some insight into why this is? It's better if I understand why this was happening. Any changes I made to the client side files such as the html files took affect immediately, it was only the server files that I had to stop then restart the nginx instance for it to take affect.
ORIGINAL POST BELOW----------------------
Any changes I make to the server side files of my deployed Node.js app with express.js isn't being seen by ubuntu. Basically, I have a mean app deployed on ubunut, it is a multipage page app, with only one of those pages having partials, so i use my routes.js
to catch the routes and send them to my main.js file to tell express and node which html or ejs file to load.
I made changes to the version on my computer so that all other routes would go to a certain html, it works great. But I pushed my changes to github, then pulled them in my ubuntu instance, and it's not working. All other changes I made to the project during this time that were pushed with it have taken affect. But, it's like ubuntu isn't letting node see any changes to the routes.js file, the code is there, I've even altered it with 'vim' from my terminal, but any changes I make, even ones that should break it, aren't seen by node. And going to an unexpected route displays the 'cannot GET...' page.
I've wracked my brain, but i'm stumped, the code is there and I can change it, I've altered html pages via vim to test it. But both, the routes.js file that handles my routing and my server.js file aren't reflecting my changes, even when I change things that should break it. Any ideas? Let me know if you need anymore info, i've included my files below. Also, I use nodemon so that it restarts automatically anytime changes are made
SERVER.JS FILE -------------------------------
var express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, './client')))
app.use(express.static(path.join(__dirname, './client/views')))
app.use(express.static(path.join(__dirname, './bower_components')))
app.set('views', path.join(__dirname, './client'));
app.set('view engine', 'ejs');
require('./server/config/routes.js')(app)
var port = 8000
app.listen(port, function(){
console.log('Server on port: ' + port)
})
ROUTES.JS FILE -----------------------------
var Main = require('../serverControllers/main.js')
module.exports = function(app){
app.get('/', Main.main)
app.get('/contact', Main.contact)
app.get('/algorithms', Main.algorithms)
app.get('/projects', Main.projects)
app.get('*', Main.other)
app.use(Main.other)
}
MAIN.JS FILE ----------------------
module.exports = {
main: function(req, res){
res.render('index')
},
contact: function(req, res){
res.render('contact')
},
algorithms: function(req, res){
res.render('algorithms')
},
projects: function(req, res){
res.render('projects')
},
other: function(req, res){
res.render('default')
},
}
I try to connect backend (NodeJS, Express) with Frontend (Angular 2), but have a problem.
When I start two servers separately, both client-side and server-side work fine.
In my situation:
localhost:4200 - Angular
localhost:3000 - NodeJS, Express
When I render any static html file in my VIEWS folder, it works correctly, but when I change the content of the html file to Angular Index.html, that uses components, it doesn’t work. I mean, it works, but doesn't load my components.
I suppose that problem is in the configuration, and my index.html doesn't know how to find and load components, but I don’t understand exactly where a mistake might be.
When I try to start both servers at the same port, my frontend part stops working.
I use Angular-CLI, NodeJS, Express and EJS.
My server.js code is:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view enjine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use('/', index);
app.use('/api', tasks);
app.listen(port, function () {
console.log('Server started on port ' + port);
});
In the ROUTES folder my index.js code is:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
My folders structure:
Picture of foldes
node_modules
routes
ruen-app
views
package.json
server.js
ruen-app is my client (Angular 2) folder.
So, my questions are:
How to connect these two parts?
Is it correct to start two servers at the same time - one for the frontend, another for the backend?
What is the best practice for MEAN applications to start from the scratch? I mean, what is the best way - two servers or one?
Spent 3 days, but found the solution.
On the stackoverflow:
Different ports for frontend and backend. How to make a request?
Angular-CLI proxy to backend doesn't work
I'd like send a parameter and render a html file when the user go to the home page of my app.
Here is what I did so far:
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
console.log('Hi !'); // never displayed
res.render('index', { foobar: 'foobar'});
});
The HTML is properly rendered (probably due to express.static) but app.get('/') seems to be never called so I can't return the variable.
How can I return a variable from a call to '/' with the static HTML page public/index.html?
My ultimate goal is to be able to use foobar in my JS without any additional call to the server. Could you help me to achieve this?
If you have a file named index.html in your public/ directory, express.static() will return that file if the url / is requested, so your route handler will never get passed the request.
Generally, templates are stored in a separate directory than static (public) resources. Express, by default, will look for templates in the ./views directory (unless you tell it otherwise) so if you move your index.html to there it will get rendered by EJS (but see below), and you can use your parameters in it.
Since EJS will by default look for files ending with a .ejs extension, if you want to keep on using .html, you need to set up Express as follows:
var ejs = require('ejs');
...
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
This tells Express to look for files with extension .html in the ./views directory, and to render those files using EJS.
var express = require('express');
var router = express.Router();
router.get('/index',function(req,res){
res.sendFile(path.resolve('./public/index.html'));
});
module.exports = router;