【发布时间】:2018-01-05 04:41:10
【问题描述】:
由于 cors 限制,我目前正在努力在 NodeJS 中获取网页的 HTML 源代码。使用 JQuery 我正在向期望 HTML 响应的页面发出 GET 请求。然而,这会引发错误XMLHttpRequest cannot load https://www.reddit.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access。有没有办法使用 NodeJS 绕过 CORS? (比如通过代理)
$.ajax({
url: 'https://www.reddit.com/',
headers: {
'Content-Type': 'text/html',
"Access-Control-Allow-Origin": '*'
},
type: "GET",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
我也在使用带有以下标头的 webpack 开发服务器
headers: {
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
}
【问题讨论】:
-
不要使用 jQuery,使用 Node.js
http模块或像 npm 包superagent这样的包装器 -
尝试使用
https://cors-anywhere.herokuapp.com/https://www.reddit.com/作为您的$.ajax url,有关说明,请参阅stackoverflow.com/questions/20035101/… -
您是否尝试通过抓取 Reddit 来获取内容?我相当肯定你最好使用他们的 API。
-
这个问题的标题应该是如何在前端请求中绕过 CORS
标签: javascript jquery node.js webpack