Node.js + Express without using Jade - node.js

Is it possible to use express without any template engine?

Yes,
app.get('/', function(req, res){
res.render('index.html');
});
should just work

UPDATED
Some might have concerns that sendFile only provides client side caching. There are various ways to have server side caching and keeping inline with the OP's question one can send back just text too with send:
res.send(cache.get(key));
Below was the original answer from 3+ years ago:
For anyone looking for an alternative answer to PavingWays, one can also do:
app.get('/', function(req, res) {
res.sendFile('path/to/index.html');
});
With no need to write:
app.use(express['static'](__dirname + '/public'));

For anyone having the need to immediately use regular HTML without jade in a new express project, you can do this.
Add a index.html to the views folder.
In app.js change
app.get('/', routes.index);
to
app.get('/', function(req, res) {
res.sendfile("views/index.html");
});
UPDATE
Use this instead. See comment section below for explanation.
app.get('/', function(req, res) {
res.sendFile(__dirname + "/views/index.html");
});

You can serve static files automatically with Express like this:
// define static files somewhere on top
app.use(express['static'](__dirname + '/your_subdir_with_html_files'));
Actually this should be express.static(...) but to pass JSLint above version works too ;)
Then you start the server and listen e.g. on port 1337:
// app listens on this port
app.listen(1337);
Express now serves static files in /your_subdir_with_html_files automatically like this:
http://localhost:1337/index.html
http://localhost:1337/otherpage.html

This is all out of date - correct answer for 3x, 4x is
The second answer here:
Render basic HTML view?

In your main file:
app.get('/', function(req, res){
res.render('index');
});
Your index.jade file should only contain:
include index.html
where index.html is the raw HTML you made.

Related

NodeJS Express — Serve generated index.html public file without saving it

When using express, the expectation is that you'll serve a public directory.
const app = express();
app.use('/', express.static('./public/'));
Is there a way I could serve a generated file instead? For my application, it would be much more convenient if I could build the index.html directly, then serve that 'file' directly from memory, without having to save it just to then serve it via 'use'.
the expectation is that you'll serve a public directory
I don't think that is the expectation at all. Many applications just use routes instead making a REST micro service.
There are two ways you can do what you want to do.
Use a templating engine with NodeJS and just res.render() the template. Check this out for more information, even though the article is using .pug you can use these ones as well. Popular ones are ejs, handlebars
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
Or you can write everything inside res.send() for example:
app.get('/', function (req, res) {
//set the appropriate HTTP header
res.setHeader('Content-Type', 'text/html');
//send multiple responses to the client
res.send('<h1>This is the response</h1>');
});

App.js functionality loss over public internet using NODE JS AND EXPRESS

Node js + express is displaying great on localhost. My issue is, is that after I display static page which is doing it's job, my app.js script is not firing from the outside world. But when running locally it works like it is suppose to.
//send html page to user
app.use(express.static(__dirname + '/node_modules'));
app.use(express.static('public'));
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/index.html'); //send the file
});
//My app
// everything below this line does not work
I followed the direction from express but still app.js is not firing from the outside world. Again it hits great on local. Any help that would be greatly appreciated!
https://expressjs.com/en/starter/static-files.html
Based on your code, I was able to deduce that you are behind a sockets enabled CDN and it has not cashed your server-side sockets. Turn off cashing if you are actively developing your site.

Prerender.io not caching pages

I have made an app with AngularJS with an expressJS backend. Now I want to make it crawlable and I've found prerender.io. I think I've done everything correct bur for some reason I don't see any statistics in the prerenderer dashboard.
In my app.configure function I've included the token like follows:
app.use(require('prerender-node').set('prerenderToken', 'my-token'));
And in my HTML I've included the meta-fragment tag:
<meta name="fragment" content="!">
The last ting I've done was to tell AngularJS to use a hashprefix:
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
But for some reason, if I refer to the documentation, I don't get the correct result. Below you can see what it is supposed to do:
Google sends a request to your server like this:
http://www.example.com/?_escaped_fragment_=/user/123
You turn the url back into this:
http://www.example.com/#!/user/123
For some reason if I try this it still adds the #! signs add the end of the URL, so if I request the URL of my app like google I get this:
http://www.my-website.com/?_escaped_fragment_=#!/home
So it does not replace the hash in the url. I think this is the cause of my problem.
Thanks in advance!
Edit - if I for example add an extra route then it works:
app.get('/', function (req, res) {
res.sendfile('./public/index.html');
});
app.get('/test', function (req, res) {
res.sendfile('./public/index.html');
});
the '/' route doesn't work the '/test' route does work.
Ok I solved my problem. The '/' route was never called because I had an index.html file inside my webpublic folder. I renamed this to public.html and changed the '/' route to get this file instead of the index.html file.
app.get('/', function (req, res) {
res.sendfile('./public/public.html');
});

res.sendfile() doesn't serve javascripts well

I want to use static file serve without any rendering engine.
I've tried to use:
res.sendfile('public/index.html');
on the '/' GET route, and express middleware for static files on my route:
app.use(express.static(path.join(__dirname, 'public')));
BUT it seems like all of the javascripts which the client asks for are downloaded with index.html file information.
How can I make a successful download of the CSS/JS static files ?
UPDATE:
Here is the route for the "res.sendfile ..." :
app.get('/*', index);
I want all of the requests to the server on any route will get index.html and all of its JS&CSS assosiciated with.
I guess this might help you...
in app.js file...
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use("/styles", express.static(__dirname + '/public/stylesheets'));
app.use("/scripts", express.static(__dirname + '/public/javascripts'));
app.use("/images", express.static(__dirname + '/public/images'));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/home.html');
});
save the home.html inside the /public folder and JavaScript files in /public/javascripts, images in /public/images, css files in /public/stylesheets folder.
In the HTML file reference should be the words you define(eg: /scripts/home.js)... like this
<link rel="stylesheet" type="text/css" href="/styles/home.css" >
<script src="/scripts/home.js" type="text/javascript"></script>
var express=require("express");
var app=express();
app.use('/', express.static(__dirname + '/website/views/'));
app.set("views",__dirname+'/website/views');
app.get("/",function(req,res){
res.sendfile('index.html');
});
the codes above is mine.i wish to help you.
Why not something like this?
if(req.url == '/') { // Root lookups appear to be mapped to index.html
next();
} else {
fname = [disk location of your website] + req.url;
fs.open(fname, 'r', function(err, fd) {
if(err) {
next();
} else {
fs.close(fd);
res.sendfile(fname);
}
});
}
Well, the simplest solution will be to move app.use(express.static(path.join(__dirname, 'public')))
up before you call app.use(app.router);
This way, the static middleware gets served before the app.get('/*', index);
I've made an assumption here that your routes are declared in this order:
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
If this is indeed the case, then the following suggestion holds:
The problem here is the app.get('/*', …) will intercept all requests that match, which is basically everything. Your static middleware won't get a chance at serving files.
If you remove that route, things should work for you as index.html is already in the public directory and can be served by the static middleware.
For a good explanation of how this works, see the answer to this question: node.js / express.js - How does app.router work?
Update based on additions to the above question:
You've stated this as the current behavior of your server:
it seems like all of the javascripts which the client asks for are downloaded with index.html file information.
You have asked the question:
How can I make a successful download of the CSS/JS static files ?
with this requirement
I want all of the requests to the server on any route will get index.html and all of its JS&CSS assosiciated with.
Your question and requirement are opposed to each other. The server will send back to the client exactly what you tell/configure it to. It will either always send back index.html which is exactly what your requirement states, or it will successfully serve up both index.html and any CSS/Javascript it references which is what your original problem statement was.
In one of your comments below you've stated:
the reason I want to do it, is because I'm using templates, and index.html wraps each template. I'm using angular on the client, and I'm starting to realize that i'll have to use a render engine in order to achieve this. Again, my angular client defines the partial url, and when it sends the request to : '/partial/sample' I need the index.html to wrap the 'sample.html' for instance
My assumptions based on this statement (please correct if wrong)
You are using client side templates
The files you are retrieving from the server are static (i.e., they need to be served up as is from the server)
Your routes are currently declared in this order
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
You are not doing any server side templating (i.e. everything is located under public somewhere)
If these assumptions are correct, the fix is to do what I originally suggested and remove this route:
app.get('/*', index);
If you do this (assuming your resources are referenced correctly):
your index.html will be retrieved as is from the server via the static middleware.
Each css/js file you've referenced in index.html will be returned from the server via the static middleware
Any requests to load template files (such as sample.html) will be serviced by your static middeware and returned to the client without modification

node.js with express - showing custom error message

I am using node.js and express and I want to show custom error message when the requested page is not found. Currently I am doing it by using a Wildcards. If any of the routes doesn't match then the last route gets invoked. Is there any other better way to do this??
My routes
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/*', error.error);
What you are doing is good. The only thing I would change is the order of routes like so
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/', routes.index);
app.get('/*', error.error);
A good rule to follow is define all least general routes first. As you probably know this basically tells express that if no other route is found show an error message and wild cards are a pretty good way to do it.

Resources