javascript - 发出 GET 请求时出错 "Failed to load resource: net::ERR_CONNECTION_REFUSED"

标签 javascript node.js macos express xmlhttprequest

对此非常陌生,但我正在尝试测试一个小应用程序,该应用程序对本地主机服务器 http://localhost:3000/golfpool-standings 上的快速端点执行 GET 请求。并使用返回的 JSON 在 html 表中显示数据,但是当我尝试在脚本中使用时,我得到 无法加载资源:net::ERR_CONNECTION_REFUSED 我正在实时服务器 http://127.0.0.1:5500/golfApp/index.html 上进行测试 即使在这里查看了类似的答案后,我也遇到了困难。任何帮助表示赞赏。我的第一个问题请温柔一点。

我可以访问端点http://localhost:3000/golfpool-standings从 Chrome 浏览器返回的 JSON 显示在屏幕上,因此看来后端正在工作。 https://github.com/paulcullen79/golfApp

// index.js
    const data = $.getJSON("http://localhost:3000/golfpool- 
    standings")

// server.js
    const express = require('express')  
    const app = express()

app.get('/golfpool-standings', (req, res) => {
    res.send(data)
})

const port = process.env.port || 3000
app.listen(port, () => console.log(`Listening on port ${port}...`))

最佳答案

此行 $.getJSON("http://localhost:3000/golfpool-stands") 正在请求 json 资源,但您的服务器未提供服务json.

来自 jQuery 文档:

As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.

更改您的服务器代码:

app.get('/golfpool-standings', (req, res) => {
  // send data as json
  res.json(data)
})

或者将您的请求更改为 $.get("http://localhost:3000/golfpool-stands")

关于javascript - 发出 GET 请求时出错 "Failed to load resource: net::ERR_CONNECTION_REFUSED",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562837/

相关文章:

objective-c - NSTextField 后面的 NSCollectionViewItem

objective-c - 将一个透明的 NSWindow 永久地放在另一个 NSWindow 之上

c - Mac OS 和 FreeBSD 之间 kqueue 处理 fifo 的差异?

javascript - 如何为我的站点创建水平滑动子菜单面板?

javascript - DIV 重叠。需要把它移过去,这样他们就不会

node.js - 如何使用Selenium chromedriver而不强制更新?

node.js - 查找 Node 包上次更新的时间

javascript - 在 javascript 和 jquery 中使用原型(prototype)函数中构造函数中传递的变量

javascript - 在 Aptana 中使用关键字作为对象键会引发语法错误

javascript - 在我的应用程序启动时创建所有路由是个好主意吗?