i have a problem opening a js-file on my NodeJS-server, because it will always specify my .js-file with a Content-Type of "text/html".
The goal is to send user-input from a html-form to a JavaScript-file for doing some calculations and later create a Graphic from it.
On my app.js (Node-Server) i have:
const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' })
fs.readFile('index.html', function(error, data) {
if (error) {
res.writeHead(404)
res.write('Error: File Not Found')
} else {
res.write(data)
}
res.end()
})
})
This will open my html-file correctly. Which is an input-form like follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="module" src="./js/index.js"></script>
<title>Node-App</title>
</head>
<body>
Enter Name and Birthdate:<br><br>
<form action="#" method="post" id="frm">
<label for="Name">Name:</label><br>
<input type="text" id="nam"><br>
<label for="Date">Date:</label><br>
<input type="text" id="dat"><br>
<input type="button" onclick="userInput()" value="Plot">
</form>
But now i want to open a js-function from here by clicking a button, which gives me the error "userInput is not defnied".
Not a surprise, since loading the page already throw the error "Loading the Module from "www/js/index.js" was blocked by a disabled MIME-Type (text/html)"
My JS-file looks like this, but is not loaded correctly anyways:
function userInput() {
console.log("Test The Function");
}
I can see in "Network Analysis", in the .js-files's http-header, that its Content-Type is "text/html", so my question is how can i change this?
I tried several things already like setting it in my app.js by typing res.writeHead(200, { 'Content-Type': ['text/html', application/javascript] })
or res.setHeader("Content-Type": "application/javascript");
but it would either not load the html anymore or just do nothing.
Also i tried to set the Content-Type in my index.html as a script-tag like <script type="application/javascript" src="./js/index.js"></script>
, but it also changes nothing.
Thanks for your help!