I use passport.js to authenticate user after he enters login page. To keep user logged in when he returns to home page i'm going to use something like:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
if(req.user){
// connect to database ....
} else{
res.sendFile(__dirname +'/index.html');
}
});
Note that index.html file is inside "public" folder. Recently i realized that having a code like above, node.js doesn't use app.get('/'....) route but it serves index.html directly. So i'm unable to check if req.user exists. Any suggestion?
As You might understand express.static handles index.html before Your router.
But You cannot avoid express.static also (otherwise You have to use nginx or write own static file output).
So You've to re-think Your folder structure or have to develop 2 separate apps: api (backend) and frontend (that will request to api for data)
In context of Your question I wrote an example app where I organize assets, html files and app routes:
1) Have such folder structure:
2) and example app.js :
'use strict';
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
app.set('trust proxy', 1);
// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html'); // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder
// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());
// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
req.user = {id: 1, username: 'test'};
next();
};
app.get('/', authorizeUser, (req, res) => {
res.render('index', {user: req.user}); // render get index.html from views folder (see above)
});
app.listen(8080, () => {
console.log('App listening');
});
p.s. download example app from here (don't forget to call npm i inside extracted folder (; )
p.s. implement passport.js Yourself
Related
How do i stop access to index .html file and let people sign up on home.ejs, i was building a static website but now making a web app and want people to sign up.
i commented out the index section but still the index gets on first instead of home.
I want people to sign up first and then use the app
This is my code.
//jshint esversion: 6
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
/* app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "public", "index.html"));
}); */
app.get("/home", function(req, res){
res.render("home")
})
app.listen(3000);
console.log('now the server is running')
App using static assets from public which includes your index.html file.
You can remove index.html from a static source
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
Or you can give a base path to static folder.
app.use('/public' ,express.static(path.join(__dirname, 'public')));
when I enter in http://localhost/client, display 404.
app.get('/client', function(req, res) {
...
ejs.render('any template', {});
...
res.end();
});
app.get('*', function(req, res) {
console.log('404');
...
});
but if I remove "ejs.render" and put res.end('any html') works.
How can i use "ejs.render" and not call 404? Thanks. It's a bug.
You need to set ejs for use EJS with express.
The Express application generator uses Jade as its default, but it also supports several others (Like ejs, pug, etc).
For example:
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/client', function(req, res) {
res.render('pages/index'); //does not needs ejs extension
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(8080);
console.log('8080 is the magic port');
When you make a request to the home page, the index.ejs file will be rendered as HTML.
See the official documentation here.
so I was trying to follow a tutorial to use node.js as the front end of a wordpress site
This one http://www.1001.io/improve-wordpress-with-nodejs/
Here is the code from server.js
var frnt = require('frnt');
var fs = require("fs");
var path = require("path");
var express = require('express');
var app = express();
var doT = require('express-dot');
// Define where the public files are, in this example ./public
app.use(express.static(path.join(__dirname, 'public')));
// Make sure this is set before the frnt middleware, otherwise you won't
// be able to create custom routes.
app.use(app.router);
// Setup the frnt middleware with the link to the internal server
app.use(frnt.init({
proxyUrl: "http://localhost:8888/frnt-example/wordpress", // The link to your wordpress site
layout: false // We simplify this example by not using layouts
}));
// define rendering engine
app.set('views', path.join(__dirname, "views"));
app.set('view engine', 'html' );
app.engine('html', doT.__express );
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('./views/index.html');
});
app.listen(8080); // listen to port 8080
It keeps outputting the following
./views/index.html
Rather than rendering the html?
I've never used frnt, but res.send sends a string so that's no big surprise.
Look at res.sendfile which sends the contents of a file.
I prefer to use ejs , it's sems like html just edit index.html to index.ejs
1- install ejs module npm install ejs
2- add this in app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
and render the index.ejs by using
app.get('/', function (req, res) {
res.render('index'); // or res.render('index.ejs');
});
res.send() // it send just a string not file
Hope it usefull !
I am developing a web app using Node.js, Express and AngularJS.
I am serving my front-end JavaScript from the public folder, so e.g. that HTTP GET /lib/angular/angular.min.js would presumably return the AngularJS JavaScript.
However, as I want all requests to get handled by the Angular router in the browser, I have a catch-all route defined as follows:
app.get('/*', function(req, res) { res.send('template.jade'); });
The problem is that this route overrides the static asset routing, in which case it always run, even when a static asset is requested.
Is there a way to tell Express to process static assets before the custom routes propagate? Are there perhaps any other clever ways of avoiding this issue?
The Express configuration is as follows:
// Generated by CoffeeScript 1.7.1
(function() {
var ExpressConfig, crypto, express, path, pkg;
crypto = require('crypto');
express = require('express');
path = require('path');
pkg = require('../package');
ExpressConfig = (function() {
function ExpressConfig() {}
ExpressConfig.prototype.configure = function(ENV) {
var APP_ROOT, app;
APP_ROOT = path.join(__dirname, '../');
app = express();
app.set('port', pkg.config.port);
app.set('views', APP_ROOT + 'webapp');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser(crypto.randomBytes(20).toString('hex')));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(APP_ROOT + 'public'));
app.use(express["static"](APP_ROOT + 'public'));
if (ENV === 'development') {
app.use(express.errorHandler());
}
return app;
};
return ExpressConfig;
})();
module.exports = ExpressConfig;
}).call(this);
//# sourceMappingURL=express-config.map
I can verify that the configuration is run before the catch-all route definition, as I have checked it by logging in each place to check the order.
I can also verify that the assets configuration works when the catch-all route is removed.
The static middleware should appear before app.router and the specific route.
// first
app.use(express["static"](APP_ROOT + 'public'));
// second
app.use(app.router);
// last
app.get('/*',whatever);
I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);