modernator modernator - 1 year ago 282
Ajax Question

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

I'm using Express for my website and using credential xhr. I want to request to
, and this is my
part in express server:

app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://*');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');

But when I try credential xhr from to, it fails with:

Fetch API cannot load
Response to preflight request doesn't pass access control check: The
' header has a value '
that is not equal to the supplied origin. Origin
'' is therefore not allowed access. Have the
server send the header with a valid value, or, if an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.

Looks like it causes from browser didn't understood what exactly
means, and refuse the request.

I want to request from these domains:





  • [anything]

I'm using Fetch API for XHR, and set
credentials: true
. Is there a something that I missed? Any advice will very appreciate it.

Answer Source

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:

app.use((req, res, next) => {
    if (req.hostname.endsWith('')) {
        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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download