提问者:小点点

为什么我的应用程序似乎正在侦听端口3501,但我的浏览器无法连接到该端口的localhost?[副本]


我正在youtube上做这个PERN教程,我遇到了以下问题。虽然我的终端显示了预期的输出,但我无法通过浏览器上的localhost访问该端口。试过火狐和Chrome。代码如下:

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: *:*

多谢了。


共1个答案

匿名用户

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

试试这个。

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