【发布时间】: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