【问题标题】:How do I start a server using nodejs?如何使用 nodejs 启动服务器?
【发布时间】:2020-12-28 03:06:14
【问题描述】:

我开始学习nodejs并在创建服务器的课程中停下来,这里是这个脚本的代码:

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) {   //create web server
    if (req.url == '/') { //check the URL of the current request
        
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' }); 
        
        // set response content    
        res.write('<html><body><p>This is home Page.</p></body></html>');
        res.end();
    
    }
    else if (req.url == "/student") {
        
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><p>This is student Page.</p></body></html>');
        res.end();
    
    }
    else if (req.url == "/admin") {
        
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><p>This is admin Page.</p></body></html>');
        res.end();
    
    }
    else
        res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

我在远程机器(谷歌云虚拟机)上进行实验,使用节点运行脚本(我在控制台中看到服务器正在运行的消息)但是如果我通过浏览器访问 IP 地址(例如@ 987654321@) 我没有看到结果,我做错了什么?没有找到任何额外的信息,在课程中到处都是通过localhost:5000/访问...

【问题讨论】:

  • 尝试收听0.0.0.0。将您的监听代码更改为 server.listen('0.0.0.0', 5000);
  • 试过了,结果“无法访问网站”
  • 您的虚拟机 VPC 是否配置为允许来自该 ip 的请求到端口?
  • 我没有额外配置任何东西

标签: javascript node.js http server nodejs-server


【解决方案1】:
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

您还可以执行以下操作:

res.end('<html><body><p>This is admin Page.</p></body></html>');

【讨论】:

  • 感谢您的建议,但这并没有解决我的问题
  • @nikobazylev 如果没有这些 if 语句,页面是否可以完美显示?
  • 没有“if” - 它也不起作用,在我看来这不是错误
  • @nikobazylev 你的 ip 正确吗?您是否尝试导航到“localhost:5000”?
  • 无法访问localhost,因为电脑是远程的,IP是举例,但我输入的地址正确
【解决方案2】:

请检查您是否能够从您的笔记本电脑终端远程登录远程服务器 IP 的 5000 端口。可能是防火墙阻止了外部访问的端口。如果你想在服务器端检查这个,你可以登录到谷歌机器并从服务器的终端尝试 curl http://localhost:5000 ,如果你看到响应,那么它应该是防火墙。

【讨论】:

  • TELNET 说:“连接到 IP.IP.IP.IP ... 无法在端口 5000 上打开到该节点的连接:连接失败”。在服务器上添加了对防火墙中端口 5000 的权限,但仍然是同样的错误
  • 您是否还使用命令 curl localhost:5000 从远程服务器终端进行了检查?你能在这里发布命令的结果吗?
  • 当通过“curl localhost:5000”向服务器请求时,响应带有页面内容——也就是正确的:“

    这是主页。

    "
  • 所以很明显问题是因为您无法使用 IP 访问端口 5000 上的 GCP 服务器。这可能主要是由于防火墙问题。您必须检查 GCP 文档以允许您正在使用的 IP 上的端口 5000,这可以解决您的问题。或者,如果您想通过浏览器进行测试,请在 GCP 服务器上安装 chrome 或 firefox,并使用 xterm 在远程服务器上打开浏览器(如果服务器是 linux),它应该可以使用 localhost:5000 在该浏览器上运行
猜你喜欢
  • 1970-01-01
  • 2018-10-30
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2014-06-01
  • 1970-01-01
  • 2017-12-29
相关资源
最近更新 更多