Rohan
Rohan

Reputation: 1190

Node.js - Serve HTML to a remote client

I am serving an HTML file from my Node.js server. The server code is -

var port = 3000;
var serverUrl = "0.0.0.0";

var http = require("http");
var path = require("path"); 
var fs = require("fs");         
console.log("Starting web server at " + serverUrl + ":" + port);

var server = http.createServer(function(req, res) {

    var filename = req.url || "/realtime-graph-meterNW.html";
    var ext = path.extname(filename);
    var localPath = __dirname;
    var validExtensions = {
        , '.css'   : 'text/css'
        , '.html'  : 'text/html'
        , '.js'    : 'application/javascript'
    };
    var isValidExt = validExtensions[ext];

    if (isValidExt) {

        localPath += filename;
        path.exists(localPath, function(exists) {
            if(exists) {
                console.log("Serving file: " + localPath);
                getFile(localPath, res, ext);
            } else {
                console.log("File not found: " + localPath);
                res.writeHead(404);
                res.end();
            }
        });

    } else {
        console.log("Invalid file extension detected: " + ext)
    }

}).listen(port, serverUrl);

function getFile(localPath, res, mimeType) {
    fs.readFile(localPath, function(err, contents) {
        if(!err) {
            res.setHeader("Content-Length", contents.length);
            res.setHeader("Content-Type", mimeType);
            res.statusCode = 200;
            res.end(contents);
        } else {
            res.writeHead(500);
            res.end();
        }
    });
}

When i try to run the HTML file from a browser on my own PC, using http://localhost:3000/realtime-graph-meterNW.html, it works fine.

But when I try to access the same from a browser on another PC on the same network using my IP address, I get an error - Failed to load resource: the server responded with a status of 503 (Service Unavailable).

I don't get where I'm going wrong with this. Any suggestions ?

Upvotes: 0

Views: 337

Answers (1)

Cristian Smocot
Cristian Smocot

Reputation: 666

Probably your local firewall is blocking connections to your machine for port 3000.

Check your firewall settings. You must allow your PC in the firewall settings to be accessible from the outside.

Also check this question and answers:

How could others, on a local network, access my NodeJS app while it's running on my machine?

Like the accepted answer says on the question I linked, you have to make sure that you put the correct URL, like for example http://192.168.3.200:3000 (if your IP is 192.168.3.200), when trying to access your server from the LAN.

Upvotes: 1

Related Questions