Node express does not render the right view - javascript

Here is my project structure
public/
css/
images/
js/
routes/
index.js
users.js
views/
AdminView/
layouts/
layout.hbs
index.hbs
I am currently having a problem where I cannot load the right view on my Node Express app. Here is some of my code
users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond');
});
router.get('/admin', function(req, res, next) {
res.render(__dirname + 'AdminView/pages/tables/job-posts', {title: 'Admin Page'});
});
module.exports = router;
app.js *a portion of it
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout' , layoutsDir: __dirname + '/views/layouts'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// Render the main view static files
app.use(express.static(path.join(__dirname, 'public'))); // Render for /
app.use("/career", express.static(__dirname + '/public')); // Render for /carrer/
app.use("/career/form", express.static(__dirname + '/public')); // Render for /carrer/form
app.use("/users", express.static(__dirname + "/views/AdminView")); // Render for /users
// Problematic code below
app.use("/users/admin", express.static(__dirname + "/views/AdminView")); // Render for /users/admin
app.use('/', routes);
app.use('/users', users);
Here is the problem. When I am trying to access /users/admin, I do not know why it renders the index page on the AdminView folder full with the css, js and images, while it should be rendering the one I specified on the routing (AdminView/pages/tables/job-posts).
Though, if I comment the line that is problematic above, it loads the html file which i specified on the routing file, but does not render the static files.
Side note:
I have 2 website, one is the main website, the other one is the admin page. All of the admin resources are on the views/AdminView folder
Full app.js http://pastebin.com/YFAbcKRz
Full users.js http://pastebin.com/TZrdFYA2
The file what I trying to load is on the picture below

Related

Serving static frontend JS file with Express JS

Hi I am having trouble Loading the frontend JS file in Express server. My file structure is like this
My Server Code -
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
});
I can successfully Load the html file
But the script file index.js is not loading and i am not able to function
<script src="index.js"></script>
Can you tell me what is it i am doing wrong
The "public" folder on the back end usually refers to a folder on the server mapped to the root path of the URL. Hence try replacing the /static path with just / in express routing, and put checks for logged in status (and any other HTTP GET request processing for server root paths that does not involve serving static files) before setting up the static server itself:
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
// set up static server on root path:
app.use('/', express.static(path.join(__dirname, 'public')))
});

How to load JS file in html using express server

I have put my js in a public directory and trying to load the js in my HTML but getting an error.
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Here is my HTML code to load the JS:
<script src="/public/web.js"></script>
directory structure
├ public
| └ web.js
├ views
| └ some.ejs
└ server.js
To serve a file from the server to the client, you must declare the directory as a static.
Using express you can do this using,
app.use(express.static('PublicDirectoryPath'))
To fetch the files under the public directory,
<script src="FilePathUnderPublicDirectory"></script>
Updated Code:
Now your server.js file should be
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
app.use(express.static('public'));
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Notice that I declare the public directory as a static directory at
line 7.
Since your web3.js is directly under the public directory, in your front end, use
<script src="/web.js"></script>
For more, please check the doc.
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
app.use(express.static('public'))
now you can serve static files like js, css and images.

Route an entire folder and its content

I want to protect a folder and its content by redirecting the user back to index.
I've tried this, but it only works partially.
var express = require('express');
var path = require('path');
var http = require('http');
var app = express();
app.set('port', 8080);
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/protected/*', function(req, res, next) {
res.redirect('/');
next();
});
//activating server
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
This routes, for example, "localhost:8080/protected" and "localhost:8080/protected/asdf", but not "localhost:8080/protected/otherPage.html".
In this case asdf is not an actual file, but otherPage.html is. So if the file is there it doesn't redirect, but if it is not then it redirects. Why is this?
Your line dealing with static files app.use(express.static(path.join(__dirname, 'views'))); appears before app.get('/protected') so its being matched first.
If you moved the static handler to later in the code this would work as you require.
However, I would recommend splitting the static items into a separate folder to guard against accidentally revealing any server-side code you might be including in ejs files in the views folder.

How can I go about serving single page html using node.js on port 80?

My project structure looks like this:
project
assets/images/
css/application.css
js/application.js
font
node_modules
index.html
server.js
package.json
My goal is to be able to run 'node server.js" in the project folder and have it serve on port 80. Going to localhost:80 or w.e would render the index.html along with its css/assets/js.
I've tried with connect, express and http but no luck...new to node.
Thanks!
First of all, change your structure:
project
assets/images/
assets/css/application.css
assets/js/application.js
assets/font
node_modules
views/index.html
server.js
package.json
First require some packages:
var express = require('express'),
app = express(),
path = require('path');
Them run in the terminal window:
npm install express
Them set up the configurations:
app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');
app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
Them create your routes:
app.get('/', function(req, res) {
res.send('Hello word');
});
app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});
If you want render the index, inside the views folder:
app.get('/index', function(req, res) {
res.render('index');
});
And finally:
app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});
Them access localhost:80/index
Put your assets and subdirs under ./public, then from top dir, add app.js:
var express = require('express');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(80, function () {
console.log('Server running...');
});

Express failing to look up view

I am trying to create a SPA app, but when i start my application it does an infinte loop leading to a crash. I am using ExpressJS 4.3.0
App architecture:
public
--partials
----index.jade
server.js
My express code:
var app = express();
var port = process.env.PORT || 8080;
app.set('views', __dirname + '/public');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.get('*', function (req, res) {
res.render('partials/index');
});
app.get('/', function (req, res) {
res.render('partials/index');
});
app.get('/partials/:name', function (req, res) {
res.render('/partials/' + req.params.name);
});
app.listen(port);
console.log('Server is running on port: ' + port);
If i use
res.render('/partials/index');
i recieve a message:
Error: Failed to lookup view "/partials/index" in views directory
Its because of view lookup function in express view lookup
if (!utils.isAbsolute(path)) path = join(this.root, path);
which makes it assume '/partial/index' is already an absolute path and didnt prefix with root path.
Also move the
app.get('*', function (req, res) {
res.render('partials/index');
});
to end else it will always serve the index view.
It looks like you shouldn't have a preceding / in your view path in render(). Just use 'partials/' + req.params.name.
On a related note, are you sure you want your actual view files to be public? Usually they are stored outside of the public static directory (e.g. ./public contains static assets and ./partials contains views). Also that way you don't have to keep prefixing view paths with partials/.

Categories