admin管理员组

文章数量:1355731

Disclaimer: I am new to node.js so I assume there is a very basic answer to this question.

I am using node.js on Windows, with http module to generate a static page with content generate from a js file.

Server file (server.js):

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

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});

HTML file (index.html):

<!DOCTYPE html>
<html>

<body>

<div id="div1">
  <p id="p1">This is a static paragraph.</p>
</div>

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

</body>
</html>

JS file (start.js)

var para = document.createElement("p");
var node = document.createTextNode("This text is loaded from a js file.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);

When I load index.html directly, I get the following output:

This is a static paragraph.

This text is loaded from a js file.

^^ this is my desired output.

Problem: However, when I use node.js and run server.js, the start.js content does not load. I get:

This is a static paragraph.

Any help would be appreciated.

FYI, my folder structure

/
- node_modules
-- http
-- fs
- index.html
- server.js
- start.js

Disclaimer: I am new to node.js so I assume there is a very basic answer to this question.

I am using node.js on Windows, with http module to generate a static page with content generate from a js file.

Server file (server.js):

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

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});

HTML file (index.html):

<!DOCTYPE html>
<html>

<body>

<div id="div1">
  <p id="p1">This is a static paragraph.</p>
</div>

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

</body>
</html>

JS file (start.js)

var para = document.createElement("p");
var node = document.createTextNode("This text is loaded from a js file.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);

When I load index.html directly, I get the following output:

This is a static paragraph.

This text is loaded from a js file.

^^ this is my desired output.

Problem: However, when I use node.js and run server.js, the start.js content does not load. I get:

This is a static paragraph.

Any help would be appreciated.

FYI, my folder structure

/
- node_modules
-- http
-- fs
- index.html
- server.js
- start.js
Share Improve this question asked Oct 1, 2018 at 5:02 WronskiWronski 1,6065 gold badges23 silver badges42 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

Every request url that you get for a file needs to be handled by the node server. I would suggest using Express.js as this would ease in handling the different url paths and files can be served directly. But in case you want a pure node.js based implementation, check below code.

To serve a file from the server you will have to modify your server.js to something like this:

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

http.createServer(function(request, response) {
    if(request.url=='/'){
        fs.readFile('./index.html', function (err, html) {
             if (err) {
                  res.send(500,{error: err});
             }
             response.writeHeader(200, {"Content-Type": "text/html"});
             response.write(html);
             response.end();
        });
    } else if(request.url=='/start.js'){
        fs.readFile('./start.js', function (err, jsFile) {
             if (err) {
                  res.send(500,{error: err});
             }
             response.writeHeader(200, {"Content-Type": "text/javascript"});
             response.write(jsFile);
             response.end();
        });
    }

}).listen(8080);

Hope this helps :)

Your logic for appending child nodes seems okay.

I think you should try changing your src="start.js" to src="./start.js" or src="/start.js" just to make sure that you're referencing the path properly. Add a console.log() statement in your start.js to make sure that it is being loaded.

EDIT: Make sure you are hosting your file on your server. You could add something like express or connect to help.

To use connect, run npm install --save connect in your project directory.

var connect = require('connect'),
directory = '/path/to/Folder'; // probably just '/' for all your files

connect()
  .use(connect.static(directory))
  .listen(80);

console.log('Listening on port 80.');

Refer to their docs for full instructions and more examples using http.

I think it's not able to find the js, Before you reference the js, ensure it is on the server and you can load it from the server, like this: 'http://127.0.0.1:8000/start.js'. All of our static files, such as img, css, js should be put on server, only then it will be referrenced.

You app not seeing your javascript file. Best solution is to use express.

  1. create public folder(if you don't have it).

  2. Put your javascript file into public folder.

    Import express.

    set static folder.

  3. In your .html file write path to .js file like you are in public folder, ex: "/public-subfolder-if-is/yourFile.js"

const express = require('express');
const app = express();

app.use(express.static("public"));

本文标签: javascript not loading in HTML filenodejshttpStack Overflow