简体   繁体   中英

node.js does not load javascript file

I am a total newbie to node.js.

My problem is that the html-file 'index.html' called as 'localhost:5000' seems not to load the javascript file 'test.js'.

I start the server by

nodejs server.js

from a shell. The files are

server.js:

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

var server = http.createServer(function (request, response) {

    if (request.url === "/") {
        fs.readFile("index.html", function (error, pgResp) {
            if (error) {
                response.writeHead(404);
                response.write('Page is not found');
            } else {
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write(pgResp);
            }

            response.end();
        });
    } else {
        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write('<h1>Default Content</h1>');
        response.end();
    }});
server.listen(5000);
console.log('Server is listening on 5000');
console.log(process.cwd())

The path process.cwd() is the path of the three files server.js, index.html and test.js

index.html:

<html>
<body>
    <center>
    <h2>Testing NodeJS Application </h2>
    <p> This is my first web application using NodeJS </p>
    </center>
    <script  type="text/javascript"  src="test.js"></script>
    <script>
      alert('Even this is a Test!');
    </script>
</body>
</html>

and test.js:

alert('I am here!');

The alert in index.html is shown, the alert in test.js is not.

I am using ubuntu 18.04.

Thanks in advance

Peter

The issue is the way you are importing the test.js script in your HTML file:

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

This file is being loaded on your browser, but the route provided in src= can't be resolved since "test.js" is not a valid URL or route to the file where you can load it from.

You should first define where are you going to expose your "test.js" file from, so it can be fetched from your browser, and then, correct the value in src= to the actual URL.

For example, a common practice is exposing public files in a /public/ folder in your server code, then expose the files in there when the URL matches such /public/**some-file.js pattern.

In your code you can achieve that by doing:

//...
var path = require('path');

var server = http.createServer(function (request, response) {

    if (request.url.startsWith("/public/")) {
        fs.readFile(path.join(__dirname, path.normalize(req.url)), function (err,data) {
          if (err) {
            res.writeHead(404);
            res.end(JSON.stringify(err));            
            return;
          }
        res.writeHead(200);
        res.end(data);
      });

      return;
    }

    if (request.url === "/") {
       // ...      
    } else {
       // ...
    }});

//... rest of your code

You can find more details in this guide: How to serve static files .

This is the final code I use. I placed the javascript file test.js in a folder named public.

var path = require('path');
var http = require('http');
var static = require('node-static');
const process = require('process'); 
var fs = require('fs');


var server = http.createServer(function (request, response) {

    if (request.url.startsWith("/public/")) {
        fs.readFile(path.join(__dirname, path.normalize(request.url)), function (err,data) {
          if (err) {
            response.writeHead(404);
            response.end(JSON.stringify(err));            
            return;
          }
        response.writeHead(200);
        response.end(data);
      });

      return;
    }

    if (request.url === "/") {
        fs.readFile("index.html", function (error, pgResp) {
            if (error) {
                response.writeHead(404);
                response.write('Page is not found');
            } else {
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write(pgResp);
            }

            response.end();
        });
    } else {

        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write('<h1>Default Content</h1>');
        response.end();
    }
});

server.listen(5000);

console.log('Server is listening on 5000');
console.log(process.cwd())

Many thanks!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM