【问题标题】:Debian server, Node js Port 3000 listening But cant access via browserDebian服务器,Node js端口3000监听但无法通过浏览器访问
【发布时间】:2021-09-07 07:21:12
【问题描述】:

在我的 debian 服务器上,我安装了 node,然后在端口 3000 上启动了 node 服务器。服务器正在运行,但从浏览器中看不到它

现在,当我尝试通过我的域或我的 ip(例如 xx.xxx.xx.xx:3000)或我的域(my-domain.com:3000)运行它时,在这两种情况下它都不会工作。我想我不太明白这个概念,我试图搜索十亿种不同的东西,但我找不到解决问题的方法。如果我还需要设置其他东西,有人可以告诉我吗?

我的服务器js代码是

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
 
server.listen(3000, () => {
  console.log('listening on *:3000');
});
io.on('connection', function (socket) {
        socket.on( 'new_message', function( data ) {
            io.sockets.emit( 'new_message', {
            message: data.message,
            date: data.date,
            msgcount: data.msgcount
            });
    });
});

Error i got

【问题讨论】:

    标签: node.js express debian


    【解决方案1】:

    您需要侦听 GET 请求才能响应它们。

    尝试添加类似的内容:

    app.get('/', function (req, res) {
      res.send('GET request test.')
    })

    在您的情况下,请确保在将app 传递给http.createServer() 方法之前添加路由,否则只需使用app.listen(3000) 之类的东西。

    文档中的更多信息:https://expressjs.com/en/guide/routing.html

    【讨论】:

    • 无法正常工作,出现错误无法访问此站点 www.mydomainame:3000 响应时间过长。
    • 等等,你是在远程 debian 机器的 localhost:3000 上运行服务器吗?
    • 这不在本地主机上,它在我的域名上
    • Server.listen(3000) === localhost:3000。你可能需要一个像 NGINX 这样的反向代理来将请求传递给快速服务器。现在您只在“您的域名”上收听本地请求。我不知道那是远程服务器还是什么...
    【解决方案2】:

    你为什么同时使用 express 和 http 两个包。

    您可以通过其中任何一个运行服务器。

    然后为其添加一条获取路线。

    import { createServer } from "http";
    import { Server } from "socket.io";
    
    const httpServer = createServer();
    const io = new Server(httpServer, {
      // ...
    });
    
    io.on("connection", (socket) => {
      // ...
    });
    
    httpServer.listen(3000);
    
    

    我希望这会奏效!

    【讨论】:

    • 您的代码给出错误警告:要加载 ES 模块,请在 package.json 中设置 "type": "module" 或使用 .mjs 扩展名。 (使用node --trace-warnings ... 显示警告的创建位置) /usr/www/users/oompfcease/server.js:1 import { createServer } from "http";
    • 在本地主机上运行时,代码运行良好,但在服务器上运行时却不行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2021-05-23
    • 1970-01-01
    • 2023-04-07
    • 2013-02-14
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多