1

I installed Node.js and wanted to run a webserver that would show an html+javascript page that imports javascript functions from other .js files. Installing Node.js, running the webserver, and hosting a file locally all went very smoothly. But I keep having issues accessing the other .js files that I would like to import from test_functions.html. I have been following various online tutorials, and looking around on stack overflow, trying it in several different ways, but can't get it to work. I am thinking I might need to adjust something in the server.js file to allow my browser to acces the other files I want to import? Using .mjs extensions (instead of .js) I got my browser to recognise the functions I want to import, but it still doesn't manage to import the functions that I define in these .mjs files.

Here is the code for server.js

// use the http library to start the node server
const { read } = require('fs')
const http = require('http')
// additional library for file handling
const fs = require('fs')
// port we want to use
const port = 3000
// filename of the html page we want to show when accessing the server
const file_name = 'test_functions.html'
// create the server

const server = http.createServer(function(req, res){
    // tell the brower we will be writing HTML
    res.writeHead(200, {'Content-Type':'text/html'})
    fs.readFile(file_name, function(error, data){
        if(error){
            res.writeHead(404)
            read.write('Error: File ' + file_name + ' not found')
        } else{
            res.write(data)
        }
        res.end()
    })
})
server.listen(port, function(error){
    if (error){
        console.log('Something went wrong', error)
    }
    else {
        console.log('Server is istenng on port ' + port)
    }
})

My main page, test_functions.html looks as follows

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="test.mjs" type="module">
        </script>
    </head>
    <body>
        <p>Hey, click on the button below to invoke the function</p>
        <input type = "button" onclick = "showAlert()" value = "Click Me">
    </body>
</html>

while the function that I placed in test.mjs looks as follows

export default function showAlert()
{
    alert("welcome");  
} 
console.log('hello')

After trying it in various ways, the browser keeps giving me the following two errors:

  • Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
  • Uncaught ReferenceError: showAlert is not defined at HTMLInputElement.onclick
2
  • 1
    Does this answer your question? Basic static file server in NodeJS Commented Jul 30, 2022 at 12:20
  • Thank you very much! I managed to get it working by expanding the server.js script to search through a public folder where it will source all requested files from. I'll update the question later when I understand a bit better what I did, but basically followed the code from the following video youtube.com/watch?v=gvbVjJnv-b8 Commented Jul 30, 2022 at 20:45

1 Answer 1

1

To allow the Node server to search through a public folder for all files that are requested by the browser I followed the following tutorial: https://youtube.com/watch?v=gvbVjJnv-b8

I got it all to work in the end by updating the server.js file as follows:

// use the http library to start the node server
const { read } = require('fs')
const http = require('http')

// additional libraries for file handling
const url = require("url");
const fs = require('fs')
const lookup = require("mime-types").lookup;

// server settings
const PORT = 3000
const DEFAULT_PAGE = index.html

// create the server
const server = http.createServer((req, res) => {
    // handle the request and send back a static file from a local folder called 'public'
    let parsedURL = url.parse(req.url, true);
    // remove the leading and trailing slashes
    let path = parsedURL.path.replace(/^\/+|\/+$/g, '');
    if (path == ""){
        path = DEFAULT_PAGE;
    }
    console.log(`Requested path ${path} `);

    let file = __dirname + "/public/" + path;
    // async read file function uses callback
    fs.readFile(file, function(err, content){
        if(err){
            console.log(`File Not Found ${file}`);
            res.writeHead(404);
            res.end();
        } else {
            //specify the content type in the response
            console.log(`Returning ${path}`);
            res.setHeader("X-Content-Type-Options", "nosniff");
            let mime = lookup(path);
            res.writeHead(200, { "Content-type": mime });
            res.end(content);
        }
    });

})
server.listen(PORT, function(error){
    if (error){
        console.log('Something went wrong', error)
    }
    else {
        console.log('Server is istenng on port ' + PORT)
    }
})
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.