javascript - Node serving blank page -


i have index.html page present at:

d:\gitprojects\codelab\complete\step1\index.html

i trying execute d:\gitprojects\codelab\complete\step1\server.js file via node:

"c:\program files\nodejs>node.exe d:\gitprojects\codelab\complete\step1\server.js"

server.js code:

var static = require('node-static'); var http = require('http'); var file = new (static.server)("d:\gitprojects\codelab\complete\step1"); var app = http.createserver(function (req, res) {   file.serve(req, res); }).listen(2011); 

when go hit: http://localhost:2011/ see empty page. idea why?

the console shows "http://localhost:2011/ failed load resource: server responded status of 404 (not found)"

you need keep file.serve(req,res) within req.addlistener()

var static = require('node-static'); var http = require('http'); var file = new (static.server)("./"); var app = http.createserver(function (req, res) {  req.addlistener('end',function(){   //   <--   file.serve(req, res); }).resume()                         //   <--   }).listen(2011); 

also, have couple of other options go with(if dont want stick node-static)

option-1: use fs module read file , send on request

var http = require('http'),     fs = require('fs');     fs.readfile('./index.html', function (err, html) {     if (err) {         throw err;      }            http.createserver(function(request, response) {           response.writeheader(200, {"content-type": "text/html"});           response.write(html);           response.end();       }).listen(2011); }); 

option-2:
use web app framework express(). provides several great features simplify power of node. can either define specific route '/' send index.html

var express= require('express') var app = express()  app.get('/',function(req,res){   res.sendfile('index.html',{ root:__dirname }) })  app.listen(2011) 

or serve static assets straightaway:

var express= require('express') var app = express()  app.use(express.static(__dirname)); //this make index.html available every request  app.listen(2011) 

__dirname directory executing script in. since both server.js , index.html @ same level, __dirname point *d:\gitprojects\codelab\complete\step1*


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -