Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Node origin even though headers are set

I have two URLs on the same server, mydomain.com and api.mydomain.com

Now in my API I have added the following to deal with access-origin:

app.use(function (req, res, next) {
    // CORS headers
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, x-access-token, Cache-Control, Pragma"
    );
    next();
});

However when ever I attempt to make a request to this API I get the following error:

XMLHttpRequest cannot load https://api.mydomain.dk/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.mydomain.dk' is therefore not allowed access.

What am I missing?

Upvotes: 0

Views: 58

Answers (1)

EMX
EMX

Reputation: 6211

The order is important, you have to do it before your routes :

Example Code :

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

I suggest using the cors express module.


EDIT :

Enable Cors Nodejs Apache

Enabling CORS on apache is a two-step process. First you must create a file with the name .htaccess and add it to the directory where your cross-domain-friendly files are. We recommend you create a new directory for this. The file must contain the following code, (lines 2 and 3 may be optional):

Header always set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The second step in the process is to enable .htaccess files. Test out the CORS requests and see if they are already working (some installations of Apache come with .htaccess files already enabled). In order to test if it’s working, reload apache (using the command below) and then fire your ajax request at your server.

sudo service apache2 restart

If that worked, you’re done. If not, then you need to add the following code inside the VirtualHosts section of your 000-default.conf in your /etc/apache2/sites-available folder:

Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all

Make sure you replace the /var/www/ with the actual path to your document root. Congrats! You’re done!

Upvotes: 1

Related Questions