从HTML加载外部.js文件

时间:2018-03-16 10:28:03

标签: javascript html node.js

我有一个简单的HTML文件,我想从中加载.js文件。 我有这些文件(文件在同一个文件夹中):

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>

和SetData.js

console.log("Its me");

我正在使用node.js,所以我用node start.js开始我的项目 在index.html中,我想用

调用本地SetData.js文件
<script type= "text/javascript" src="./SetData.js"></script>

但网上没有任何内容,只有这个错误 enter image description here

我已经尝试从另一个文件夹调用.js文件或从正文部分调用它。总是一样的错误。 如何从HTML加载本地.js文件?

2 个答案:

答案 0 :(得分:0)

你可以使用这样的东西

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

答案 1 :(得分:0)

使用以下代码替换start.js中的代码。已经回答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/');
相关问题