0

I have a simple node.js server which is meant to respond to GET requests at the address http://localhost:3000/hi/ with my index.html document, and I cannot figure out why it is reading/responding with an (index) and index.js.

My function which works with router objects is:

const http = require('http');
const path = require('path');
const fs = require('fs');

let contacts = {
    "1234": { 
        id: "1234",
        phone: "77012345678",
        name: "Sauron",
        address: "1234 Abc"
    },
    "4567": { 
        id: "4567",
        phone: "77012345678",
        name: "Saruman",
        address: "Orthanc, Isengard"
    },
};

let loadStatic = (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    fs.readFile('./index.html', null, (err,data) => {
        if (err) {
            return console.log('error');
        } else {
            res.write(data);
        }
        res.end();
    });
}

let routes = [
    {
        method: 'GET',
        url: /^\/contacts\/[0-9]+$/,
        run: getContact
    },
    {
        method: 'DELETE',
        url: /^\/contacts\/[0-9]+$/,
        run: deleteContact
    },
    {
        method: 'GET',
        url: /^\/contacts\/?$/,
        run: getContacts
    },
    {
        method: 'POST',
        url: /^\/contacts\/?$/,
        run: createContact
    },
    {
        method: 'GET',
        url: /\/hi\//,
        run: loadStatic
    },
    {
        method: 'GET',
        url: /^.*$/,
        run: notFound
    }
];


let server = http.createServer((req, res) => {
    
    let route = routes.find(route =>
        route.url.test(req.url) &&
        req.method === route.method
    );
    route.run(req, res);
});

server.listen(3000);

Request URL: http://localhost:3000/hi/index.js
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Type: text/html
Date: Mon, 20 Aug 2018 23:41:45 GMT
Transfer-Encoding: chunked

Above is the response as processed by google chrome browser. I have no idea first of all, what (index) is - it contains all my html script, along with index.js which is also sent along (presumably with the html doc), which is the name of the javascript file that's supposed to be controlling the DOM. Both contain the html script, which is not right, the .js should be different, and it attempts to read the .js first. Also, the error in the console says "unexpected '<'" which should be obvious since it's trying to read a .js file which contains nothing but .html script. I am still very new to this, and can't find an answer. Thanks for reading, and hopefully revising!

**EDIT - I added more pertinent code to the server script. Lots of redacted functions, but those all work fine. It's this one request that isn't. index.html, index.js (this file controls the DOM and gets script tags in index.html), and newserver.js (name of this file) are in the same folder on my desktop. Hope that helps.

2
  • Can you include the rest of your JS file, or pertinent details about the file structure you have in your project? Commented Aug 20, 2018 at 23:53
  • 1
    Are you sure loadStatic is getting hit? Try logging something to the console from inside that function just to check. Also, consider using the express framework, so you can simplify your setup of routes. Commented Aug 21, 2018 at 1:25

1 Answer 1

2

index.js is not "sent along" with index.html as you seem to think. The browser first requests /hi. When you send the content for that HTML file, the browser then parses that HTML file and for any <script src="xxx"> tags it finds in the HTML, the browser, then makes a separate request to your server for whatever the src file is in the script tag such as index.js.

Because you don't have a route for /index.js, it will match your notfound route (which you don't show the code for). FYI, your notfound routes should probably return a 404 status as this makes things a bit easier to debug (there will be 404 errors in the browser console which are easy to see).

You will need a route for all resources that your HTML files refer to (scripts, css files, images, etc...). node.js does not serve any files by default (unlike some other web servers). It only serves the files you specifically write routes for and write code to send.

It is possible to write a generic route that will serve any file in a specific directory that exactly matches a request. The Express framework has such as feature and is called express.static(). It is very useful for serving static resources that only need a static file sent. If you're going to continue to write your own http framework and not use one that's already been built, you will probably want to write such a static matcher. It is important, however, that you point a static file matcher at a directory that only contains public files so people can't inadvertently get access to private server files. And, one has to prevent things like .. or root paths being in the URL too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.