Reputation: 131
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:
Upvotes: 1
Views: 1998
Reputation: 131
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)
}
})
Upvotes: 1