Using wildcard for subdomain in Access-Control-Allow-Origin Using wildcard for subdomain in Access-Control-Allow-Origin express express

Using wildcard for subdomain in Access-Control-Allow-Origin


I agree with Derric's comment. The other thing though is that origin headers can be spoofed, so this is not a secure solution.

app.use(function (req, res, next) {  if (req.headers.origin.endsWith('example.com')) {    res.setHeader('Access-Control-Allow-Origin', 'http://' + req.headers.origin)    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE')  }  next()})


First off, IIRC; express documentation explicitly asks you not to use lambda expression for the middlewares.

Coming to the CORS issue, a wildcard subdomain is not valid in the context. The support was added pretty recently (in May '16), and until then, the CORS header must be an exact match of the domain name.

You can however, process your req.hostname value and add that to the response header:

// CORSapp.use(function (req, res, next) {    if (req.hostname.endsWith('example.com')) {        res.setHeader('Access-Control-Allow-Origin', 'http://' + req.hostname)        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE')    }    next()})


Adding another small adjustment here. We should also consider "protocol":

app.use(function (req, res, next) {  if (req.headers.origin.endsWith('example.com')) {    res.setHeader('Access-Control-Allow-Origin', req.protocol + '://' + req.headers.origin)    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE')  }  next()})