0

I'm currently struggling to get the HTML source of a webpage in NodeJS due to cors restrictions. Using JQuery I'm making a GET request to a page expecting an HTML response. This however throws the error 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. Is there a way to bypass CORS using NodeJS? (like via proxy)

        $.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");
        }
    });

I'm also using webpack dev server with the following headers

    headers: {
        "Access-Control-Allow-Origin": '*',
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
    }
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Bryan Charlie
  • 155
  • 2
  • 9
  • Possible duplicate of [In Node.js / Express, how do I "download" a page and gets its HTML?](https://stackoverflow.com/questions/5801453/in-node-js-express-how-do-i-download-a-page-and-gets-its-html) – Suhail Purkar Jul 29 '17 at 03:22
  • Don't use jQuery, use either the Node.js `http` module or a wrapper for it like the npm package `superagent` – Oliver Jul 29 '17 at 03:39
  • Try instead just using `https://cors-anywhere.herokuapp.com/https://www.reddit.com/`for your $.ajax url, and for an explanation, see https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource/42744707#42744707 – sideshowbarker Jul 29 '17 at 04:53
  • Are you trying to get content by scraping Reddit? I'm fairly sure you'd be better off using their API. – Matthew Daly Jul 29 '17 at 08:30
  • This question should have been titled how to bypass CORS in a front end request – Bryan Charlie Jul 29 '17 at 14:25

1 Answers1

1

Do not use jquery in nodejs, you can use this libs to archieve what you need:

Hope it helps

Sebastián Espinosa
  • 2,123
  • 13
  • 23