electrojs-远程访问节点

时间:2018-11-16 08:26:15

标签: node.js electron

我的electron.js中有一个非常基本的设置。那么我有一个js文件可以直接链接到index.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,浏览器无法找到该页面。

有什么遗漏吗?

1 个答案:

答案 0 :(得分: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