【问题标题】:Access localhost:3000 through localhost/myproject/index.html通过 localhost/myproject/index.html 访问 localhost:3000
【发布时间】:2017-05-27 11:26:51
【问题描述】:

我是 node.js 的新手,我想了解是否可以通过编写 index.html 的 url 来访问 node.js 端口(3000)。我关注this tutorial创建了一个聊天应用,但是我遇到了上面提到的问题。

我希望能够在我的浏览器上编写 localhost/myproject/index.html 而不是 localhost:3000

我的服务器端 javascript 代码是这样的:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

这里有什么我应该改变的吗?任何帮助将不胜感激。

【问题讨论】:

  • 您为什么要以这种方式使用应用程序路由会很有趣?
  • 你正在使用哪个网络服务器
  • 我使用有 apache 服务器的 WAMP
  • 使用 Apache,您可以设置一个反向代理,将请求重定向到 localhost/myproject/* 到 localhost:3000

标签: javascript node.js express socket.io localhost


【解决方案1】:

如果您想将项目作为域名而不是 localhost:3000 运行,那么只需点击此链接 https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts

【讨论】:

  • 你能用不多的话解释一下你的建议吗?另外,既然我使用的是 Windows 而不是 Ubuntu,我该怎么办?请注意,我使用 WAMP,所以我认为应该更改已经存在的文件。
【解决方案2】:

为了能够在不定义端口的情况下访问您的路径,您需要将端口 80 或端口 443 用于 https。

http.listen(80, function(){
    console.log('listening on *:80');
});

关于路径你应该调整路由参数,也可以看看express js中的static files

app.get('/myproject/index', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

【讨论】:

  • 感谢您的回答。我现在可以通过编写 localhost:3000/myproject/index.html 来访问索引。但是我怎么能像你说的那样使用80端口呢?
  • 不客气,看看更新后的问题
  • 感谢您的更新,但这不起作用。它显示了页面,但是 node.js 所做的事情不起作用。我假设我必须从设置中更改 node.js 使用的端口,或者类似的东西
  • 您在哪个系统上运行?在 linux 上你应该做sudo node ... - 你需要对低于 1024 的端口的特殊权限。
  • 我用的是windows!你知道我该怎么做吗?
猜你喜欢
  • 2014-01-23
  • 2017-11-05
  • 2021-02-09
  • 2018-06-27
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多