-1

I have a simple HTML file, from which I want to load .js file. I have these files (files are in the same folder):

start.js

var http = require('http');
var fs = require('fs');

http.createServer(function (req, response) {
    fs.readFile('index.html', 'utf-8', function (err, data) {
        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write(data);
        response.end();
    });
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
       <script src="http://mrdoob.github.com/three.js/build/three.min.js"></script>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type= "text/javascript" src="./SetData.js"></script>
        <title>main project demo</title>
    </head>
    <body>
    </body>
</html>

and SetData.js

console.log("Its me");

Im using node.js, so I start my project with node start.js In index.html I want to call local SetData.js file with

<script type= "text/javascript" src="./SetData.js"></script>

But nothing shows on web, only this error enter image description here

I already tried to call .js file from another folder or call it from body part. Always the same error. How can I load local .js file from HTML?

Haniku
  • 671
  • 1
  • 7
  • 16
  • Possible duplicate of [Node.js quick file server (static files over HTTP)](https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http) – Gabriel Bleu Mar 16 '18 at 10:59

2 Answers2

0

You can use something like this

<script src="myscripts.js"></script>
0

Replace the code in your start.js with the following code. This has already been answered here

var fs = require("fs");
var http = require("http");
var url = require("url");

http.createServer(function (request, response) {

var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");

response.writeHead(200);

    if(pathname == "/") {
        html = fs.readFileSync("index.html", "utf8");
        response.write(html);
    } else if (pathname == "/SetData.js") {
        script = fs.readFileSync("SetData.js", "utf8");
        response.write(script);
    }
    response.end();
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');
HubballiHuli
  • 777
  • 7
  • 18