繁体   English   中英

无法访问aws上的nodejs服务器

[英]Can't access nodejs server on aws

我有一个AWS EC2实例,我将其用于我的节点js应用程序。 我无法访问服务器上的任何应用程序页面。 我编写这个简单的代码仅用于测试目的,但我无法从浏览器访问它。

    var express = require('express');
var app = express();

app.listen(3000, ()=>  {
    console.log('listening');
});

app.get('/',(req,res)=>  {
    res.send('hi');
});

在导航到http://:3000时,我应该能够看到“hi”,但请求超时。 这是我的安全组配置: 在此输入图像描述

通过一些帮助解决了这个问题。 由于我可以使用的端口是端口80,所以我只是将端口8080转发到80端口。 端口转发,它解决了。 共享我找到解决方案的链接: 在aws上安装nodejs和转发端口

我的代码(如下所示)有点不同,但我从远程浏览器连接时遇到了同样的问题:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

我必须做的是用完整的AWS服务器IP替换const主机名:ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3000/

确保您的安全组中已打开端口3000,否则这将无效。

然后,我可以从我的PC上的浏览器连接到NodeJS服务器。

希望这可以帮助。 更正的代码如下所示(将x替换为您的实际IP地址。您可以在EC2仪表板上获取此代码。

const http = require('http');

const hostname = 'http://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com/';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

我得到了这个NodeJS服务器的代码:

https://websiteforstudents.com/install-the-latest-node-js-and-nmp-packages-on-ubuntu-16-04-18-04-lts/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM