-1

I would like to allow Access-Control-Allow-Origin (CORS) and ALLOW-FROM (iframe) for multiple addresses. I've looked around and found this:

Enable Access-Control-Allow-Origin for multiple domains in nodejs

and several others which say to do something like this:

const allowedOrigins = ["https://example1.com", "https://example2.com"];

if (allowedOrigins.includes(req.headers.origin)) {
    res.set("Access-Control-Allow-Origin", req.headers.origin);
    res.set("X-Frame-Options", `ALLOW-FROM ${req.headers.origin}`);
}

The problem is that req.headers.origin is always undefined, in development and production server. When I look in the Network tab of the Web Inspector, there is never a request header named origin, only host or sometimes referer.

So I tried the following:

const origin = `${req.protocol}://${req.headers.host}`;
res.set("Access-Control-Allow-Origin", origin);

This is working good, but it can't be used for the X-Frame-Options header, because host is the address on which the web resides, not the address of the iframe parent. I need ALLOW-FROM https://example1.com, not ALLOW-FROM https://myapp.com. Can you help me with it please?

lukas
  • 579
  • 2
  • 8
  • 17

1 Answers1

0

I am hoping, this is what you are looking for:

Configuring CORS w/ Dynamic Origin
var express = require('express')
var cors = require('cors')
var app = express()

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43
  • Hi, I need to set X-Frame-Options for multiple domains, so they can embed my site in an iframe. Does `cors` also set this header? It seems to have a different purporse (CORS handling). – lukas Aug 03 '18 at 11:33
  • Thank you for the tip, but how does that help me? It just seems like a more complicated way of writing `res.set("X-Frame-Options", "Deny");` – lukas Aug 03 '18 at 11:45