网站在本地工作但不在NodeJS网络服务器上,初学者

时间:2017-12-11 20:10:46

标签: javascript node.js web-services

在设置了一些文件(index.html和ws.js [设置服务器])后,我似乎无法包含我的网站使用的任何其他JS文件。我已尝试require()其他文件,但无济于事。当我运行node ws.js时,服务器出现并显示index.html,但按钮(在run.js中定义了功能)表示" replace未定义"。我通过命令node ws.js运行服务器,并通过URL localhost:8080访问网站。我最初没有模块导出,但它仍然没有工作。当我双击index.html时,我已经完成了所有这些工作,所以我知道它在本地工作(如果这是正确的术语)。

这是我的ws.js文件:

var http = require("http");
var fs = require("fs");
var events = require("events");
var serveStatic = require("serve-static");
var eventEmitter = new events.EventEmitter();

var run = require("./run.js");
run();

http.createServer(function (request, response) {
    fs.readFile('index.html', function(err, data) {
        // Send the HTTP header 
        // HTTP Status: 200 : OK
        // Content Type: text/plain
        response.writeHead(200, {'Content-Type': 'text/html'});

        response.write(data);
        return response.end();
    });
}).listen(8080);

// Console will print the message
console.log('Server running at http://127.0.0.1:8080/');
console.log(__filename);
console.log(__dirname);

(function () {
    function hi() {
        alert("This is working!");
    }
})(); 

这是我的run.js文件:

function run() {
    function testerClicked() {
        alert("Tester has been clicked!");
    }

    function replace() {
        var temp = (document.getElementById("tester").innerHTML === "This is a button." ? "This button has been pressed!" : "This is a button.");
        document.getElementById("tester").innerHTML = temp;
    }
}

module.exports = run;

这是我在HTML中调用函数的行:

<button id='tester' onclick="replace()">This is a button.</button>

很抱歉,如果这是一个基本问题。我刚开始学习服务器和JavaScript / HTML / CSS。

1 个答案:

答案 0 :(得分:1)

您目前没有从index.html文件以外的node.js服务器提供任何服务。

当您转到网页时,节点服务器中的index.html文件会响应并下载该文件。如果您的index.html中有<script src="bundle.js"></script>,则浏览器会向服务器发出另一个请求bundle.js的请求(您的ws.js文件无法处理)。尝试查看this以获取静态内容。

相关问题