簡體   English   中英

使用Nginx作為AWS EC2上的代理服務器,通過socket.io運行NodeJs應用程序

[英]Run NodeJs application with socket.io using Nginx as proxy server on AWS EC2

我正在嘗試使用Nginx作為AWS EC2上的代理服務器,通過socket.io運行NodeJs應用程序並收到以下錯誤消息:
無法加載資源:服務器以404(未找到)狀態響應/socket.io/?EIO=3&transport=polling&t=MIsbMS_:1
我正在遵循此頁面指令https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/

我的nginx設置如下:

upstream socket_nodes {
    ip_hash;
     server 127.0.0.1:8080;
}
server {
    listen 80 ;
    listen [::]:80 ;
    root /home/ubuntu/NodejsProjects/Node3;
    index index.html index.htm index.nginx-debian.html;
    server_name mydomainname.com www.mydomainname.com;
    location / {
   proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://socket_nodes;
                # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
}
}

我的index.js具有以下代碼

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

server.listen(8080);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});
  io.sockets.on('connection',function (socket){

    socket.on('test', function () {
     console.log(data);
     socket.emit('testCl', 'Test successful!!');
    });
  });

在我的index.html中

 <p id='pp'></p>
    <button id="Btn1" onclick="cc();">Get test results</button><br/>


<script>
var socket = io();
var cc=function(){
socket.emit('test');
};
socket.on('testCl', function (data) {
    console.log(data);
    $("#pp").text(data);
  });
</script>

花了幾個小時在網上搜索后,我嘗試了很多沒有成功的HTML文件操作,例如

var socket = io();
var socket = io.connect('http://localhost');
var socket = io.connect('http://localhost:8080');
var socket = io.connect('http://www.mydomainname.com:8080');
var socket = io.connect('http://myprivateIP:8080');
var socket = io.connect('http://mypublicIP:8080');

請幫忙

終於可以了。

我要做的就是在/ etc / nginx / sites中創建一個新文件-通過復制nginx默認配置文件可用

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/mynewfile

編輯該文件,並將上面給出的nginx代理設置放入其中並保存。

將此mynewfile鏈接到站點可用目錄

sudo ln -s /etc/nginx/sites-available/mynewfile /etc/nginx/sites-enabled/

現在測試了nginx文件:

sudo nginx -t

重新啟動nginx

sudo systemctl restart nginx  

以前,我正在編輯一些現有文件以用作nodejs應用程序的反向代理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM