0

I have installed a node-http-server module. I launch it from myDir on localhost port 8000. In myDir I have index.html. If I request (from the browser) http://localhost:8000/ I get index.html, which is OK and good.

If I request though http://localhost:8000/anything I do not get any response from the server.

Here's the Code I used (app.js):

const server=require('node-http-server');
var fs = require("fs");
var config = new server.Config;
config.root=__dirname;
config.server.index='index.html';

function getReq(req, res, body,enc) {
    console.log("got rewq");
    var content = fs.readFileSync('index.html', 'utf8');
    body.value = content;

}
server.deploy({port:8000});

I found that the same question asked in this link: node http-server to respond with index.html to any request . But it was for http-server module. I am using node-http-server module. I read documentation in https://github.com/RIAEvangelist/node-http-server. But can't find any suitable solutions. Help me with Some solutions.

Paul Steven
  • 93
  • 4
  • 13
  • If you intend to only respond with your index.html, why do you need anything more that vanilla node? The getting started example has this behavior. https://nodejs.org/en/docs/guides/getting-started-guide/ – JDunken Jan 06 '20 at 14:27
  • @JDunken, I have linked a JS in index.html. In the JS, there are various routers. The index.html gets me to home page. In home page, I have a top navigation bar which route to several pages. It was working great and it was navigating properly. But when I type a certain url `http://localhost:8000/anything` in the address bar, I do not get any response from the server. it shows 404. – Paul Steven Jan 06 '20 at 15:41
  • have you tried `server.onRequest=getReq;` before `server.deploy()`? https://www.npmjs.com/package/node-http-server#onrequest – JDunken Jan 06 '20 at 16:08

1 Answers1

0

To start exploring your problem i would look at your code first.

const server=require('node-http-server');
var fs = require("fs");
var config = new server.Config;
config.root=__dirname;
config.server.index='index.html';

function getReq(req, res, body,enc) {
    console.log("got rewq");
    var content = fs.readFileSync('index.html', 'utf8');
    body.value = content;

}
server.deploy({port:8000});

GetReq() function clearly should do what you expect it to do but i dont see where you actually supply node-http-server witht his function to be called as a callback. Now lets fix your code.

const server=require('node-http-server');
var fs = require("fs");
var config = new server.Config;
config.root=__dirname;
config.server.index='index.html';

function getReq(req, res, body,enc) {
    console.log("got rewq");
    var content = fs.readFileSync('index.html', 'utf8');
    body.value = content;

}
server.deploy({port:8000}, getReq);

In short you didnt read documentation for the module, you need to pass your callback function as an option to deploy method. server.deploy({port:8000}, getReq);