Ans*_*hul 2 amazon-ec2 amazon-web-services node.js
我有一个用于节点js应用程序的AWS EC2实例。我无法访问服务器上的任何应用程序页面。我仅出于测试目的编写了此简单代码,但即使从浏览器也无法访问。
var express = require('express');
var app = express();
app.listen(3000, ()=> {
console.log('listening');
});
app.get('/',(req,res)=> {
res.send('hi');
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我的代码(如下所示)有点不同,但我在从远程浏览器连接时遇到了同样的问题:
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}/`);
});
Run Code Online (Sandbox Code Playgroud)
我要做的就是用完整的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}/`);
});
Run Code Online (Sandbox Code Playgroud)
我从以下位置获取了此 NodeJS 服务器的代码:
| 归档时间: |
|
| 查看次数: |
2751 次 |
| 最近记录: |