Ad

Trying To Enable CORS: Require Is Not Defined Error

- 1 answer

Tl;dr: I'm getting a require is not defined error in the Chrome JS console, despite having installed node.js and requrejs.


I am trying to access API keys in an external JSON file using the following code in main.js:

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

readTextFile("../secrets.json", function(text){
    var data = JSON.parse(text);
    apiKey = data.api_key;
    username = data.username;
});

and since I use an XMLHttpRequest to the API later, which has an http:// scheme, I am looking to use CORS to work around the same-origin policy.

I put these lines at the beginning of main.js:

var cors = require('cors')

var app = express()
app.use(cors());

and my directory structure looks like this:

/project
  index.html
  secrets.json
  /scripts
    main.js
    require.js

In the JS console on Chrome I get a require is not defined error. Where have I gone wrong?

Ad

Answer

This code:

var cors = require('cors')

var app = express()
app.use(cors());

Belongs in a node.js server. It is not to be run inside of Chrome. It's purpose is to help you create an http server that can ACCEPT cross origin http requests from a browser.

A browser will only allow a cross origin XMLHttpRequest if the server itself that you are trying to make the request from specifically allows that cross origin request. So, it would be whatever server that supports the URL you are trying to make the XMLHttpRequest to allows cross origin requests (typically by supporting CORS). If the server does not already support your cross origin call, you would have to either modify that server's code or make the request through some sort of proxy that you do have access to that will get the data for you and relay it back to the browser.

Where have I gone wrong?

Well, the require('cors') along with the other two lines of code you show below it are not meant to run in a browser. They run in a node.js environment and would be used to create an http server that you could then connect to from some outside agent (like a browser's web page).

From the browser, you can't do anything to MAKE a server accept cross origin requests if the server isn't already configured to do so. Your only two options are to change the target server or to use a proxy.

Ad
source: stackoverflow.com
Ad