I've created a webpage to use it locally. I have a ton of routes like the ones shown below -- 31 .ejs files and 3 .html files. (They are all in the same "views" folder).
//app.js - using node and express
app.get('/page1', function(req, res){
res.render('page1');
});
app.get('/page2', function(req, res){
res.sendFile('views/page2.html', { root: __dirname });
});
I use an app.get for each and every one of these files. I've had a feeling it wasn't DRY code, and so now I'm trying to figure out a more elegant and optimal way to achieve the same result.
I know that many res.sendFile(); could be replaced with a single express.static() middleware statement. I usually use express.static() on a "public" folder which I use to save all my css files -- like this app.use(express.static(path.join(__dirname, 'public')));. But I still don't see how I could use this to simplify all my res.sendFile().
As for the many res.render(); routes, I know that if I don't pass any customized data I could probably replace them with a single middleware that handles either a whole directory of template files (and their corresponding routes) or a list of files. I just don't know how I would do that.
Any help is very much appreciated, thanks!!
[UPDATE]
richie node_modules public
css files, images, etc views
partials
all partial files programmingPublic
all ejs files from a same topic other files (html & other ejs) appjs
packagejson package-lockjson
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// engine
app.set("view engine", "ejs");
// Set static path
app.use(express.static(path.join(__dirname, 'public')));
const fs = require('fs');
function renderStatic(dir) {
return function(req, res, next) {
let target = path.join(dir, req.path);
fs.access(target, fs.constants.R_OK, function(err) {
if (err) {
// file not found, just move on
next();
} else {
res.render(target);
}
});
}
}
app.use(renderStatic(path.join(__dirname, "views/programmingPublic")));
Below is the format of my side-menu: (all these files are inside "programmingPublic" folder)
Programming
<li>C</li>
<li>C++</li>
<li>Python</li>
<li>JavaScript</li>
<li>PHP</li>
If you have a bunch of pages that need to call res.render(), but aren't passing custom options to each render, then you could isolate all those templates in their own directory and then use some middleware like this:
const path = require('path');
const fs = require('fs');
function renderStatic(dir, options) {
const regex = /^\.|\.\.|\/\.|\\\./;
options = options || {};
return function(req, res, next) {
let target = path.join(dir, req.path);
if (options.ext && !path.extname(target)) {
target = target + options.ext;
}
// don't allow leading dot or double dot anywhere in the path
if (regex.test(target)) {
next();
return;
}
fs.access(target, fs.constants.R_OK, function(err) {
if (err) {
// file not found, just move on
next();
} else {
res.render(target);
}
});
}
}
app.use(renderStatic(path.join(__dirname, "renderPublic"), {ext: ".ejs"}));
Note, you must isolate these template files in their own directory so that other files are not found there.
For safety completeness, this code also needs to filter out . and .. items in the path like express.static() does to prevent an attacker from going up your directory hierarchy to get access to other files than those in the render static directory.
Then, for the routes you are using res.sendFile() and no other logic, just isolate those HTML files in their own directory and point express.static() at that directory. Then, the express.static() middleware will find a matching HTML file in that directory and do res.sendFile() for you automatically, exactly the same as it does for your CSS files.
Related
I am trying to serve images from an "images" file in my project depending on the parameters that the user enters.
For example,
https://localhost:3000/images?fileName=burger
should display the image on the browser
does anyone know how i can go about it?
My structure is as follows:
images
---burger.jpg
src
---index.ts
I tried to do it this way but for some reason it won't work
app.use('/images', express.static('images'));
if(req.query.fileName === "burger"){
res.sendFile("burger.jpg" , {root: path.join("./images")});
}
According to your code, if your file structure is following.your code will run perfectly. make sure you set the path to serving static files under express.static() with care and note that your incoming query value exactly matches the file you need to get including the case. this should solve the problem, thank you!
File Structure:
images
--- burger.jpg
index.js
import express from 'express';
import path from 'path'
const app = express();
const PORT = process.env.PORT || 5000;
app.use('/images', express.static('images'));
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile("rocket.jpg" , {root: path.join("./images")});
})
app.listen(PORT, () => {
console.log('Server is up and running on PORT: ${PORT}');
})
you can also avoid all those fuss by removing that middleware and instead provide absolute path while sending file. for eg:
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile(path.join(__dirname, "images/Rocket.jpg"));
}
})
I'm a beginner in Express. So I might've failed to frame the question properly. I have created a MEAN application wherein I've separated my frontend and backened. Frontend runs on port:4200 and server runs on port:3000. I wanted to run both frontend and backend on same port as part of deployment. I'm getting MIME type errors, someone told me that there is some problem with my server environment. Maybe I'm not sending headers properly. Here is my code:
I have mentioned tried solutions in the code itself as <----TRIED THIS
server.js
const express = require('express');
express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS
const bodyParser = require('body-parser');
const path = require('path');
// express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS
const api = require('./routes/api');
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('/', function(req, res) {
// res.send('Hello from the server'); <----TRIED THIS
// res.writeHead(200, {'Content-Type': 'text/html'}); <----TRIED THIS
// res.set('Content-Type', 'text/plain'); <----TRIED THIS
// res.setHeader("Content-Type","application/json"); <----TRIED THIS
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})
app.listen(PORT, function() {
console.log('Server listening on PORT '+PORT);
});
api.js
For instance I'm showing you GET function only
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const db = <my db string>;
const jwt = require('jsonwebtoken');
mongoose.connect(
...
)
function verifyToken(req, res, next) {
...
}
router.get('/myarticles', (req, res) => {
var person="Tanzeel Mirza";
console.log('Get request for tanzeel articles');
Article.find({contributor: person}, (error, article) => {
if(error) {
console.log(error)
}
else {
if(!article) {
res.status(401).send('Invalid email')
}
else if(2>4) {
console.log("test passed");
}
else {
res.json(article);
}
}
})
})
module.exports = router;
But still I'm getting
Loading module from “http://localhost:3000/runtime-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/polyfills-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/main-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Please correct me.
PS: I asked separate questions for MIME error here. But no answers.
Since your assets are inside dist/application folder, Use app.use(express.static(path.join(__dirname, 'dist/application')));
To match all web app routes, Use app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
}).
This a generic route and will be called into action only if express can't find any other routes and always serve index.html. For example any valid /api route will never reach this handler, as there a specific route that handles it.
Final code for server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./routes/api');
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist/application')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})
app.listen(PORT, function() {
console.log('Server listening on PORT '+PORT);
});
A few points to not.
To serve static files, you need not set any headers manually. Express looks up the files in the folder (dist folder in your case) you set as static directory with the express.static middleware function. Express also sets the response headers based on the file extension.
So you don't need express.static.mime.define in your code anymore.
In your case you have defined app.use(express.static(path.join(__dirname, 'dist'))); which listens for static files at dist folder. In this app.use command, you haven't used a mount path which means that all the requests will go through the static middleware. If the middleware finds an asset with the same name, path and extension in dist folder it returns the file, else the request is passed to the other route handlers.
Also, If you are using static middleware, as long as there is an index.html in dist folder (immediate child of dist folder), your route handler for "/" will never get invoked as the response will be served by the middleware.
If you don't have an index html file in dist folder(immediate child of dist), but it's present somewhere in subfolders of dist, and still you need to access it using root path "/", only then you need a route handler for path "/" as below.
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "dist/application/index.html"));
});
JS files referred using "./" in dist/application/index.html are referred relative to dist folder itself and NOT dist/application folder.
You can refer this REPL for updated code 👉.
https://repl.it/repls/SoreFearlessNagware
Try below urls
/api/myarticles - Rendered by "/api" route handler
/api/myarticles.js - Rendered by static asset middleware because the file exists in dist/api folder
/ - rendered using "/" route handler and res.sendFile because index.html doesn't exist in dist folder.
/test.js - Rendered using static middleware because file exists in dist folder
Additional links for reference.
https://expressjs.com/en/api.html#res.sendFile
https://expressjs.com/en/starter/static-files.html
1.Build your angular project, either inside or outside the server folder using ng build cmd.
2.To build your project inside server, change the dist-folder path in angular-cli.
3.To change path, either use cli cmd or edit the angular-cli.json file's "outDir": "./location/toYour/dist"
Or by using this cli cmd ng build --output-path=dist/example/
4.Then In your server root file include the static build/dist folder using express.
5.Like this app.use(express.static(path.join( 'your path to static folder')));
6.Now restart your server.
So I have server.js file that imports a router
const path = require("path");
const express = require("express");
const app = express();
const PORT = 8080;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(require('./app/routing/htmlRoutes'));
The router looks like this
const path = require("path");
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.sendFile('home.html', { root: path.join(__dirname, '../public') });
});
router.get('/survey', function(req, res) {
res.sendFile('survey.html', { root: path.join(__dirname, '../public') });
});
module.exports = router;
It does work! It renders html pages, however those html pages have css stylesheets hooked up to them and located in the same directory, but they render as blank html sheets (unstyled)...
How do I make them render with css stylesheets taken into account?
When the browser encounters the style reference of the loaded html file, it tries to load the file specified in the src attribute. Now your server script doesn't have a route for that. It will load the css if you add a route for that specific css file. However as Irshad said, the standard way to do this is to add a route for all the static files.
app.use(express.static("public"))
Right now, you are only sending home.html everytim the root is requested.
Change your code to read the requested file from the req and serve that file whatever it may be.
Why not set the middleware to serve static files (css, html) from public folder app.use(express.static("public"))
See the working example
Here is my folder structure:
I have everything inside the src folder, src/index.html is what I'm trying to point too. And my node server file is in src/server/server.js
When I run the correct node src/server/server command I get the following error:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
app.get('/category', (req, res) => {
res.end('Categories');
});
app.listen(8999, (res) => {
console.log(res);
});
Error: ENOENT: no such file or directory, stat '/Users/leongaban/Projects/CompanyName/appName/src/server/index.html'
So the error message is telling me I need to go 1 more folder up, so figured something like the following:
app.get('/', (req, res) => {
res.sendFile('../index.html', { root: __dirname });
});
However now I get a Forbidden error:
ForbiddenError: Forbidden
The reason you get a Forbidden error is because Node.js finds the relative path ../ malicious (for example if you get a file based on user input he might try to reach files on your file system which you don't want him to access).
so instead you should use the path module like pointed in this question
Your code should use path like so:
var path = require('path');
res.sendFile(path.resolve(__dirname + '../index.html'));
I had a similar problem with a mean stack problem earlier on.
Mor Paz' above answer should work. :)
Just to contribute, i did the following.
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile('../index.html');
});
I'm trying to serve a folder of static mustache files from Express, but can't seem to figure out how to get it working. Say I just have an object of data like
{
a: 'Hello :)'
b: 'Goodbye :('
}
And two files,
public/a.html
<div>{{a}}</div>
public/b.html
<div>{{b}}</div>
How could I get express setup to where it serves any arbitrary number of static html files and replaces the templated parts with just my one big object? Thanks!
Static files are usually only called static when they are not processed in any way before sending to user.
What you're trying to achieve is a typical templating system. You can just follow instructions in the plugin:
var mustacheExpress = require('mustache-express');
// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', __dirname + '/views'); // you can change '/views' to '/public',
// but I recommend moving your templates to a directory
// with no outside access for security reasons
app.get('/', function (req, res) {
res.render('a');
});
Also consider using Handlebars, it's often more convenient to use than Mustache. You can find a list of differences in this question.
You can use mustachejs just like pug in express by setting mustache as view engine and defining its working like below code:
//required files
const fs = require("fs")
const mustache = require("mustache")
// To set functioning of mustachejs view engine
app.engine('html', function (filePath, options, callback) {
fs.readFile(filePath, function (err, content) {
if(err)
return callback(err)
var rendered = mustache.to_html(content.toString(),options);
return callback(null, rendered)
});
});
// Setting mustachejs as view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','html');
//rendering example for response
app.get('/',(req,res)=>{
res.render('index',{data:'Sample Data'});
});
I modify zlumer's answer a little bit and the following code works fine for me.
const express = require('express');
const app = express();
const mustacheExpress = require('mustache-express');
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.get('/', function(req, res) {
const data = {
hello: 'world',
foo: 'bar'
};
res.render('test', data);
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Please check https://github.com/HemingwayLee/sample-mustache-express
and feel free to clone and modify it.
You should not include your html files in the public directory. Public Directory should contain only images, javascript and css files.
Though there are many ways to structure the node/express application, but you can find one good way using Express Generator.
http://expressjs.com/en/starter/generator.html
If you use this, it will create the app structure for you which clearly explains how you should keep you static files.