2017-07-29 67 views
-1

由于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? (如通过代理)在NodeJS中获取页面的HTML源代码

 $.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" 
    } 
+0

可能重复[在Node.js/Express中,如何“下载”一个页面并获取其HTML?](https://stackoverflow.com/questions/5801453/in-node -js-express-how-do-i-download-a-page-and-gets-its-html) –

+0

不要使用jQuery,使用Node.js的'http'模块或者像npm这样的包装器软件包'superagent' – Tobsta

+0

请尝试使用'https://cors-anywhere.herokuapp.com/https://www.reddit.com/'for您的$ .ajax网址,有关解释,请参阅https:// stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource/42744707#42744707 – sideshowbarker

回答

0

不要使用jQuery的的NodeJS,你可以使用这个库来archieve你需要什么:

希望它有帮助