0

I'm using Webpack to bundle my javascript code and use modules in the browser.

I'm trying to get the body of a URL (http://www.redbubble.com); however, I get the following error:

XMLHttpRequest cannot load http://www.redbubble.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

This is the code I am bundling and making my request to grab the body html for http://www.redbubble.com (including this in my ejs under script tag reference)

var request = require('request');

var options = {
  url: 'http://www.redbubble.com',
  withCredentials: false
};

function callback(error, response, body) {
    window.console.log("callback is being called");
  if (!error && response.statusCode == 200) {
    alert(body);
  } else {
    window.console.log(error);
  }
}

request(options, callback);

I am also trying to use the CORS module in my app.js to resolve the Acces-Control-Allow-Origin error, but it's no good.

app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false
})); 

Why is this error persisting? And how can it be resolved?

Rohit Tigga
  • 2,373
  • 9
  • 43
  • 81
  • "I am also trying to use the CORS module in my app.js" — Your `app.js` is running on `localhost:3000`, not on `www.redbubble.com` – Quentin Nov 30 '16 at 08:59
  • @Quentin can you clarify? What exactly should I do then? – Rohit Tigga Nov 30 '16 at 09:22
  • Setting the headers did not fix the error – Rohit Tigga Nov 30 '16 at 09:26
  • "Setting the headers did not fix the error" — How did you change them? Do you work for redbubble and have access to their servers? – Quentin Nov 30 '16 at 09:30
  • So I read: "There is nothing you can do in your client-side code that will enable CORS access to someone else's server." I'm trying to figure out how exactly I should do this now? – Rohit Tigga Nov 30 '16 at 09:32
  • Maybe look at the "Alternatives to CORS" section of the accepted answer on the duplicate. – Quentin Nov 30 '16 at 09:33

1 Answers1

-1

I guess you are missing the OTIONS in the methods like this:

app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE, OPTIONS",
  "preflightContinue": false
})); 

The explanation why you need it can be found here: Understanding cors You need to make the OPTIONS method available because it is used amongst the server and the client in order to negotiate the call.

pinturic
  • 2,253
  • 1
  • 17
  • 34