electronjs - 远程访问nodejs

问题描述 投票:0回答:1

我的electron.js有一个非常基本的设置。然后我有一个直接链接到jsindex.html文件:

app.js

  const http = require('http');
  var url = require('url');
  var fs = require('fs');
  const hostname = '127.0.0.1';
  const port = 3000;
  http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "example.html";
  fs.readFile(filename, function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(port, hostname,()=>{
    console.log(`Server running at http://${hostname}:${port}/`);
});

到目前为止,我可以使用同一台计算机访问example.html访问localhost:3000

但我想用其他设备连接到这个example.html。所以我认为应该是直截了当的。首先,我需要找出local IP

var os = require('os');
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}
console.log(addresses);

我得到192.168.0.200,这是我的wifi路由器提供给我的电脑的ip。然后,我尝试通过浏览器使用URL example.html访问192.168.0.200:3000,浏览器找不到该页面。

有什么遗漏?

node.js electron
1个回答
0
投票

事实证明,这是相当直接的。我只需要用提供的IP路由器替换127.0.0.1

///get the ip from the router
var os = require('os');
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}
console.log(addresses);///<-- addresses is an array

 const http = require('http');
  var url = require('url');
  var fs = require('fs');
  const hostname = addresses[0];///<-- first element of addresses
  const port = 3000;
  http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "example.html";
  fs.readFile(filename, function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(port, hostname,()=>{
    console.log(`Server running at http://${hostname}:${port}/`);
});

那么,你可以从任何设备做192.168.0.200:3000/example.html

© www.soinside.com 2019 - 2024. All rights reserved.