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.