![](/img/trans.png)
[英]error when making GET request to 'http://localhost:3000/' “Failed to load resource: net::ERR_CONNECTION_REFUSED … delete.js”
[英]Failed to load resource: net::ERR_CONNECTION_REFUSED when fetching from localhost
我正在尝试向本地主机服务器发出请求,但收到错误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
控制台中... 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)
})();
任何帮助都会很棒。
我认为该错误是由跨域问题引起的。 您对CORS标头有误解。 标头不是由请求使用,而是由响应使用。
如果javascript程序正在发出跨域请求,则浏览器将首先向服务器发送带有相同参数的OPTION请求。 如果服务器上的后端认为请求合法,则仅包含CORS标头的响应将发送回浏览器,然后浏览器针对当前环境检查CORS标头。 如果CORS标头合适,浏览器将最终将实际请求发送到服务器,否则抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.