Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 368 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Node.js as a simple web server

#1
I want to run a very simple HTTP server. Every GET request to `example.com` should get `index.html` served to it but as a regular HTML page (i.e., same experience as when you read normal web pages).

Using the code below, I can read the content of `index.html`. How do I serve `index.html` as a regular web page?

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(index);
}).listen(9615);


----------

One suggestion below is complicated and requires me to write a `get` line for each resource (CSS, JavaScript, images) file I want to use.

How can I serve a single HTML page with some images, CSS and JavaScript?
Reply

#2
I think the part you're missing right now is that you're sending:

Content-Type: text/plain

If you want a web browser to render the HTML, you should change this to:

Content-Type: text/html

Reply

#3
Edit:
-----
Node.js sample app **Node Chat** has the functionality you want.
In it's [README.textfile][1]
3. Step is what you are looking for.


> step1
>
> - create a server that responds with hello world on port 8002
>
> step2
>
> - create an index.html and serve it
>
> step3
>
> - introduce util.js
> - change the logic so that any static file is served
> - show 404 in case no file is found
>
> step4
>
> - add jquery-1.4.2.js
> - add client.js
> - change index.html to prompt user for nickname

Here is the [server.js][2]

Here is the [util.js][3]


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#4
Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:

var contentTypesByExtension = {
'html': "text/html",
'js': "text/javascript"
};

...

var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
Reply

#5
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);

//Just Change The CONTENT TYPE to 'html'
Reply

#6
I use below code to start a simple web server which render default html file if no file mentioned in Url.

var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic Geek Files.htm';


http.createServer(function(req, res){

var fileName = url.parse(req.url).pathname;
// If no file name in Url, use default file name
fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;

fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
if (content != null && content != '' ){
res.writeHead(200,{'Content-Length':content.length});
res.write(content);
}
res.end();
});

}).listen(8800);
It will render all js, css and image file, along with all html content.

Agree on statement "**No content-type is better than a wrong one**"
Reply

#7
I found a interesting library on npm that might be of some use to you. It's called mime(`npm install mime` or

[To see links please register here]

) and it can determine the mime type of a file. Here's an example of a webserver I wrote using it:





var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path = unescape(__dirname + req.url)
var code = 200
if(fs.existsSync(path)) {
if(fs.lstatSync(path).isDirectory()) {
if(fs.existsSync(path+"index.html")) {
path += "index.html"
} else {
code = 403
resp.writeHead(code, {"Content-Type": "text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
}
resp.writeHead(code, {"Content-Type": mime.lookup(path)})
fs.readFile(path, function (e, r) {
resp.end®;

})
} else {
code = 404
resp.writeHead(code, {"Content-Type":"text/plain"});
resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at

[To see links please register here]

")

This will serve any regular text or image file (.html, .css, .js, .pdf, .jpg, .png, .m4a and .mp3 are the extensions I've tested, but it theory it should work for everything)
<h1>Developer Notes</h1>

Here is an example of output that I got with it:

Listening at

[To see links please register here]

GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg
Notice the `unescape` function in the path construction. This is to allow for filenames with spaces and encoded characters.
Reply

#8
This is basically an updated version of the accepted answer for connect version 3:

var connect = require('connect');
var serveStatic = require('serve-static');

var app = connect();

app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);

I also added a default option so that index.html is served as a default.
Reply

#9
A slightly more verbose express 4.x version but that provides directory listing, compression, caching and requests logging in a minimal number of lines


var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express

var app = express();

var oneDay = 86400000;

app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))

app.listen(process.env.PORT || 8000);

console.log("Ready To serve files !")
Reply

#10
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
// change the to 'text/plain' to 'text/html' it will work as your index page
res.end(index);
}).listen(9615);

I think you where searching for this. In your index.html, simply fill it with normal html code - whatever you want to render on it, like:

<html>
<h1>Hello world</h1>
</html>

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through