So I'm learning backend and I'm doing a simple express.js experiment. I'm using a simple GET HTTP Protocol to preview an HTML (index.html). I'm working in replit.com and I could see the preview of the index.html file that is created:
I could also get a JSON respond from a code that I've wrote if I go to link my-replit-link.co/json. This is the javascript code that I've wrote to preview the index.html and preview json on '/json' using express.js:
let express = require('express');
let app = express();
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + "/views/index.html");
})
app.get('/json', function (req, res) {
res.json({
"message": "Hello json"
})
module.exports = app;
But I'm trying to do it also in VSCode. Is there any way I could preview like in replit.com using VSCode?
Any helpful answer would be very appreciated, thanks!
I am trying to use express to render a few different html files from my public folder. These are all static files. I also want to render a 404 page if a route is an invalid route is called. Here is my code.
const express = require("express")
const app = express()
app.use(express.static("public"))
app.get("/", (req, res) => {
res.render("index")
})
app.get("/about", (req, res) => {
res.render("about")
})
app.get("/contact-me", (req, res) => {
res.render("contact-me")
})
app.get("*", (req, res) => {
res.status(404).send("404 for all pages not defined in routes")
})
app.listen(8080)
The first route to render index.html works and the 404 status works, but all the other routes give me an error of "No default engine was specified and no extension provided." I tried added an ejs view engine, but the code still doesn't work. All html files are named properly and live in the "public" folder. Any help on this would be amazing! Thanks much!
You need to use handlebars for handling it. To see an example check this repo
I'm trying to set up a simple routing app but I keep running int the error when rendering a page.
Error: Module "html" does not provide a view engine.
What is odd is I've specified the view engine in my app.js file but I'm still getting the error
// app.js
var express = require('express');
var app = express();
var router = express.Router();
// Need to import the route file
var chef = require('./chef');
app.use('/chef', chef);
// Set directory to contain the templates ('views')
app.set('views', __dirname + '/views');
// Set view engine to use
app.set('view engine', 'html');
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// chef.js
var express = require('express');
var routes = express.Router();
routes.get('/', (req, res) => {
//res.send("I'm here!")
res.render('chef');
});
module.exports = routes;
// views/chef.html
Some HTML file here here ..
In the chef.js file when I just want to test if the route is working I uncomment res.send ... which sends "I'm here" to the DOM.
However whenever I try res.render to render the chef.html page I get the error above. Which I find odd because I've set the view engine in app.js.
Suggestions on how to render my HTML file?
use res.sendFile('/fileName.html'); instead of res.render()
for sending file , we used res.sendFile(fullPath) and if you are using other than HTML language then you should have to use res.render().
res.render() for template like ejs, pug etc.
I am learning expressjs and I've been stuck at moment how to make the navigation between pages:
What I've done:
1. Installed express, and converted regular html to jade format.
2. In app.js I've added following code:
app.get('/', function(req, res){
res.render('views/index.jade', { title: 'index' });
});
app.get('/about', function(req, res){
res.render('views/portfolio.jade', { title: 'about' });
});
All files I've stored in views folder and in index.jade I've added following code:
a.selected(href='/views/index.jade') TIMELINE
a(href='/views/portfolio.jade') PORTFOLIO
a(href='/views/about_me.jade') ABOUT ME
a(href='/views/store.jade') STORE
When I click on portfolio button, the following error appears:
You need to link href the route path:
a.selected(href='/') TIMELINE
a(href='/about') PORTFOLIO
a(href='/about') ABOUT ME
a(href='/store') STORE
You are actually creating routes, which enable a browser to ask the server for data on a specific path. What the server sends to the browser based on that path is up to the programmer.
In your case, you're internally configuring the /about route to render the file views/portfolio.jade.
Thus, instead of linking to the .jade files like you're doing, you should be linking to the actual routes you created:
a.selected(href='/') TIMELINE
a(href='/portfolio') PORTFOLIO
a(href='/about') ABOUT ME
a(href='/store') STORE
Assuming you have the following routes:
app.get('/', function(req, res){
res.render('views/index.jade', { title: 'index' });
});
app.get('/about', function(req, res){
res.render('views/about_me.jade', { title: 'about' });
});
app.get('/store', function(req, res){
res.render('views/store.jade', { title: 'store' });
});
app.get('/portfolio', function(req, res){
res.render('views/portfolio.jade', { title: 'portfolio' });
});
I want to render raw .html pages using Express 3 as follows:
server.get('/', function(req, res) {
res.render('login.html');
}
This is how I have configured the server to render raw HTML pages (inspired from this outdated question):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(str, options) {
return function(locals) {
return str;
};
});
Unfortunately, with this configuration the page hangs and is never rendered properly. What have I done wrong? How can I render raw HTLM using Express 3 without fancy rendering engines such as Jade and EJS?
What I think you are trying to say is:
How can I serve static html files, right?
Let's get down to it.
First, some code from my own project:
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
What this means that there is a folder named public inside my app folder. All my static content such as css, js and even html pages lie here.
To actually send static html pages, just add this in your app file
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/layout.html');
});
So if you have a domain called xyz.com; whenever someone goes there, they will be served layout.html in their browsers.
Edit
If you are using express 4, things are a bit different.
The routes and middleware are executed exactly in the same order they are placed.
One good technique is the place the static file serving code right after all the standard routes.
Like this :
// All standard routes are above here
app.post('/posts', handler.POST.getPosts);
// Serve static files
app.use(express.static('./public'));
This is very important as it potentially removes a bottleneck in your code. Take a look at this stackoverflow answer(the first one where he talks about optimization)
The other major change for express 4.0 is that you don't need to use app.configure()
If you don't actually need to inject data into templates, the simplest solution in express is to use the static file server (express.static()).
However, if you still want to wire up the routes to the pages manually (eg your example mapping '/' to 'login.html'), you might try res.sendFile() to send your html docs over:
http://expressjs.com/api.html#res.sendfile
Have you tried using the fs module?
server.get('/', function(req, res) {
fs.readFile('index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
as the document says : 'Express expects: (path, options, callback)' format function in app.engin(...).
so you can write your code like below(for simplicity, but it work):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(path, options, cb) {
fs.readFile(path, 'utf-8', cb);
});
of course just like 2# & 3# said, you should use express.static() for static file transfer; and the code above not suit for production
First, the mistake you did was trying to use the express 2.x code snippet to render raw HTML in express 3.0. Beginning express 3.0, just the filepath will be passed to view engine instead of file content.
Coming to solution,
create a simple view engine
var fs = require('fs');
function rawHtmlViewEngine(filename, options, callback) {
fs.readFile(filename, 'utf8', function(err, str){
if(err) return callback(err);
/*
* if required, you could write your own
* custom view file processing logic here
*/
callback(null, str);
});
}
use it like this
server.engine('html', rawHtmlViewEngine)
server.set('views', './folder');
server.set('view engine', 'html');
Reference
Official express 2.x to 3.x migration guide
See 'Template engine integration' section in this url
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
After a fresh install of the latest version of Express
express the_app_name
Creates a skeleton directory that includes app.js.
There is a line in app.js that reads:
app.use(express.static(path.join(__dirname, 'public')));
So a folder named public is where the magic happens...
Routing is then done by a function modeled this way:
app.get('/', function(req,res) {
res.sendfile('public/name_of_static_file.extension');
});
*Example:*
An index.html inside the public folder is served when invoked by the line:
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
As far as assets go:
Make sure the css and javascript files are called from the folder relative to the public folder.
A vanilla Express install will have stylesheets, javascripts, and images for starting folders. So make sure the scripts and css sheets have the correct paths in index.html:
Examples:
<link href="stylesheets/bootstrap.css" rel="stylesheet">
or
<script src="javascripts/jquery.js"></script>
You can render .html pages in express using following code:-
var app = express();
app.engine('html', ejs.__express);
And while rendering, you can use following code:-
response.render('templates.html',{title:"my home page"});
I wanted to do this because I'm creating a boilerplate NodeJS server that I don't want tied to a view engine. For this purpose it's useful to have a placeholder rendering engine which simply returns the (html) file content.
Here's what I came up with:
//htmlrenderer.js
'use strict';
var fs = require('fs'); // for reading files from the file system
exports.renderHtml = function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
if (err) return callback(new Error(err));
var rendered = content.toString();
// Do any processing here...
return callback(null, rendered);
});
};
To use it:
app.engine('html', htmlRenderer.renderHtml);
app.set('view engine', 'html');
Source: http://expressjs.com/en/advanced/developing-template-engines.html
Comments and constructive feedback are welcome!
After years a new answer is here.
Actually this approach like skypecakess answer;
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.send(html)
})
That's all...
Also if EJS or Jade will be used the below code could be used:
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.render('login', { html: html })
})
And views/login.ejs file contains only the following code:
<%- locals.html %>
app.get('/', function(req, res) {
returnHtml(res, 'index');
});
function returnHtml(res, name) {
res.sendFile(__dirname + '/' + name + '.html');
}
And put your index.html to your root page, of course you could create a /views folder for example and extend returnHtml() function.
You can send file using res.sendFile().
You can keep all html files in views folder and can set path to it in options variable.
app.get('/', (req, res)=>{
var options = { root: __dirname + '/../views/' };
var fileName = 'index.html';
res.sendFile(fileName, options);
});