为什么我的应用程序似乎正在侦听端口 3501,但我的浏览器无法连接到该端口上的本地主机?

问题描述

我正在 youtube 上执行此操作 PERN tutorial,但遇到了以下问题。尽管我的终端显示了预期的输出,但我无法通过浏览器上的 localhost 访问该端口。已经尝试过火狐和铬。代码如下:

require("dotenv").config();
const express = require("express");
const app = express();

app.get("/getRestaurants",(req,resp) => {
  console.log("get all restaurants");
});

//http://localhost:3501/getRestaurants

const port = process.env.PORT || 3500;
app.listen(port,() => {
  console.log(`server is up and listening on port ${port}`)
});

而命令行中的输出是:

server is up and listening on port 3501
get all restaurants

但是当我尝试导航到 http://localhost:3501/getRestaurants 时,它会永远加载。 ss -tlwn 的输出显示它也在监听:

 - Netid: tcp
 - State: LISTEN
 - Recv-Q: 0
 - Send-Q: 511
 - Local Address: Port:*:3501
 - Peer Address:Port: *:*

谢谢。

解决方法

当您尝试从浏览器连接到服务器时,为了加载页面,您的浏览器应该得到响应。由于您没有从服务器返回任何数据以进行请求,因此您的浏览器会等待并且很可能在一段时间后超时。

试试这个。

app.get("/getRestaurants",(req,resp) => {
    console.log("get all restaurants");
    resp.send("get all restaurants");
});