簡體   English   中英

Node.js-將HTML提供給遠程客戶端

[英]Node.js - Serve HTML to a remote client

我正在從Node.js服務器提供HTML文件。 服務器代碼是-

var port = 3000;
var serverUrl = "0.0.0.0";

var http = require("http");
var path = require("path"); 
var fs = require("fs");         
console.log("Starting web server at " + serverUrl + ":" + port);

var server = http.createServer(function(req, res) {

    var filename = req.url || "/realtime-graph-meterNW.html";
    var ext = path.extname(filename);
    var localPath = __dirname;
    var validExtensions = {
        , '.css'   : 'text/css'
        , '.html'  : 'text/html'
        , '.js'    : 'application/javascript'
    };
    var isValidExt = validExtensions[ext];

    if (isValidExt) {

        localPath += filename;
        path.exists(localPath, function(exists) {
            if(exists) {
                console.log("Serving file: " + localPath);
                getFile(localPath, res, ext);
            } else {
                console.log("File not found: " + localPath);
                res.writeHead(404);
                res.end();
            }
        });

    } else {
        console.log("Invalid file extension detected: " + ext)
    }

}).listen(port, serverUrl);

function getFile(localPath, res, mimeType) {
    fs.readFile(localPath, function(err, contents) {
        if(!err) {
            res.setHeader("Content-Length", contents.length);
            res.setHeader("Content-Type", mimeType);
            res.statusCode = 200;
            res.end(contents);
        } else {
            res.writeHead(500);
            res.end();
        }
    });
}

當我嘗試使用http://localhost:3000/realtime-graph-meterNW.html從自己的PC上的瀏覽器運行HTML文件時,它工作正常。

但是,當我嘗試使用IP地址從同一網絡上另一台PC上的瀏覽器訪問同一瀏覽器時,出現一個錯誤- Failed to load resource: the server responded with a status of 503 (Service Unavailable)

我不明白我要怎么做。 有什么建議么 ?

可能是您的本地防火牆阻止了端口3000與計算機的連接。

檢查您的防火牆設置。 您必須允許從外部訪問防火牆設置中的PC。

還要檢查此問題和答案:

本地網絡上的其他人如何在我的機器上運行我的NodeJS應用程序時訪問它?

就像接受的答案在我鏈接的問題上說的那樣,在嘗試訪問您的主機時,必須確保輸入正確的URL,例如http://192.168.3.200:3000 (如果IP為192.168.3.200)。局域網中的服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM