Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic webserver with node.js and express for serving html file and assets

I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):

var express = require('express'),     app = express.createServer();  app.configure(function(){   app.use(express.static(__dirname + '/static')); });  app.get('/', function(req, res){   res.sendFile(__dirname + '/index.html'); });  app.listen(3000); 

Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?

like image 348
djevg Avatar asked Feb 25 '12 12:02

djevg


People also ask

How do I serve HTML in node js?

The open source text editor Brackets also includes a NodeJS static web server. Just open any HTML file in Brackets, press "Live Preview" and it starts a static server and opens your browser at the page. The browser will auto refresh whenever you edit and save the HTML file.

Can you create an HTTP web server with node js?

The Node. js framework can be used to develop web servers using the 'http' module. The application can be made to listen on a particular port and send a response to the client whenever a request is made to the application.

Which web server is used for node js?

You can use IIS or Apache to run Node. js web application but it is recommended to use Node. js web server.

Can Express serve HTML?

Delivering HTML files using Express can be useful when you need a solution for serving static pages.


1 Answers

I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):

app.get('/', function(req,res) {   res.sendfile('public/index.html'); }); 
like image 176
ajventi Avatar answered Sep 19 '22 15:09

ajventi