我正在尝试向我的本地主机服务器发出请求,但收到错误消息 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);
}
});
});
我自己做了一些研究,指出使用我的私有(private) 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)
})();
任何帮助都会很棒。
最佳答案
我认为错误是由跨域问题引起的。您对 CORS header 有误解。 header 不被请求使用,而是被响应使用。
如果javascript程序发起跨域请求,浏览器会先向服务器发送一个具有相同参数的OPTION请求。如果服务器后端认为请求是合法的,则将仅包含 CORS header 的响应发送回浏览器,然后浏览器根据当前环境检查 CORS header 。如果 CORS header 合适,浏览器最终会将真正的请求发送到服务器,否则会抛出错误。
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
关于javascript - 无法加载资源:net::ERR_CONNECTION_REFUSED 从本地主机获取时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389768/
相关文章:
reactjs - GraphQL 返回数据但在代码中未定义
visual-studio-app-center-distribute - 是否可以在 AppCen
jpa - Spring Data JPA Projection嵌套列表投影接口(interface
javascript - 是否可以禁用整个主体(包括内部 iFrame)的填写付款表格?
javascript - 错误 [prerender-spa-plugin] - 无法预呈现所有路线
android - 如何在 kotlin 中使用 http 请求将图像上传到服务器?
reactjs - 在 React BootStrap 中的行元素之间添加空格