2017-07-29 48 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你需要什麼:

希望它有幫助

相關問題