【问题标题】:Failed to load resource: net::ERR_CONNECTION_REFUSED when fetching from localhost无法加载资源:从 localhost 获取时 net::ERR_CONNECTION_REFUSED
【发布时间】:2019-08-07 16:47:54
【问题描述】:

我正在尝试向我的本地主机服务器发出请求,但收到错误 Failed to load resource: net::ERR_CONNECTION_REFUSED。

这是我的前端代码:

(async () => {
    const data = await fetch('http://localhost:8080/articles/', {
        headers: { "Access-Control-Allow-Origin": "http://localhost:8080/articles/" }
    });

    const articles = await data.json()

    console.log(articles)
})();

和后端代码:

app.get("/articles/", function (req, res) {
    let inputValue = req.body.page;
    let pages = Math.ceil(totalResults / 10)
    page = scripts.iteratePages(inputValue, page, pages);

    request("https://newsapi.org/v2/top-headlines?q=" + initialQ +
        "&category=sports&pageSize=10&page=" + page + "&sortBy=relevance&apiKey=" +
        apiKey, function (error, response, body) {

            if (!error && response.statusCode == 200) {
                let data = JSON.parse(body);
                let articles = scripts.articlesArr(data);
                res.json({ articles: articles });
            } else {
                res.redirect("/");
                console.log(response.body);
            }
        });
});

我自己进行了一些研究,这表明使用我的私有 IP 地址而不是 localhost 并且在控制台中收到 ... is not a function 错误:

let ipAddress = "blah.blah.blah.blah"

    (async () => {
        const data = await fetch('http://' + ipAddress + ':8080/articles/', {
            headers: { "Access-Control-Allow-Origin": "http://" + ipAddress + ":8080/articles/" }
        });

        const articles = await data.json()

        console.log(articles)
    })();

任何帮助都会很棒。

【问题讨论】:

  • 您的端点没有返回 json。使用res.json({ filtered: articles }) 代替res.render 和res.redirect
  • 谢谢。但是控制台仍然返回Uncaught TypeError: "ip address goes here" is not a function
  • 代码在哪一行发现错误?
  • 如果您的服务器在您的机器上,localhost 应该可以正常工作。我的猜测是您使用了错误的端口。或者您的服务器没有启动(或崩溃)
  • @Seblor 嘿伙计,是的 - 我的本地主机正在运行端口 3000,而不是 8080 - 新手错误。现在可以了。谢谢

标签: javascript node.js


【解决方案1】:

我认为该错误是由跨域问题引起的。您对 CORS 标头有误解。标头不是由请求使用,而是由响应使用。

如果javascript程序进行跨域请求,浏览器会先向服务器发送一个参数相同的OPTION请求。如果服务器上的后端认为请求是合法的,则将仅包含 CORS 标头的响应发送回浏览器,然后浏览器根据当前环境检查 CORS 标头。如果 CORS 标头合适,浏览器最终会将真正的请求发送到服务器,否则会抛出错误。

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

【讨论】:

  • 错误是连接被拒绝,而不是 CORS 错误。 Plus OP 在本地主机中遇到问题并使用服务器。如果您尝试从 file:// 访问 http(s) 服务器,CORS 问题只会在 localhost 中发生,它会显示 CORS 异常,而不是连接被拒绝错误
  • @Seblor 你的假设并不正确,cors - 跨域资源共享 - 确实发生在每个主机上,而不仅仅是 localhost 并且与 file:// 无关。我同意你的观点,这里的错误与 CORS 无关。
猜你喜欢
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 2015-04-02
  • 1970-01-01
  • 2021-11-15
  • 2023-02-22
相关资源
最近更新 更多