Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS Regex in Node Express Server

I am creating an express server. This is the snippet.

const app = express();
app.use(cookieParser()); // mainly used to retrieve and store CSSO tokens
app.use(bodyParser.json());

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "https://the.real.url.com:8081");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Expose-Headers", "Content-Disposition, Content-Type");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});

It is working currently. But I need to replace https://the.real.url.com:8081 with regex. First, it can be https or just http. Second, there may or may not be a port. and so forth.

So when I edited it https?://the.real.url.com:8081 to allow both http and https.

I get this error The 'Access-Control-Allow-Origin' header contains the invalid value 'https?://the.real.url.com:8081'. Origin 'https://the.real.url.com:8081' is therefore not allowed access.

I also tried http(s?)://the.real.url.com:8081, https?://*, and other variations. None of them works.

So I am wondering Regex is not allowed? But the wildcard * works.

Am I doing something wrong?

like image 539
william Avatar asked Jul 20 '26 01:07

william


2 Answers

Have you looked at the cors package for express: https://github.com/expressjs/cors, this allows you to use a regex for the origin:

var express = require('express');
var cors = require('cors');
var app = express();

var corsOptions = {
  origin: /example\.com$/,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
};

app.use(cors(corsOptions));

You can also use this package on individual endpoints,e.g.

app.get('/test/', cors(corsOptions), function (req, res, next) {
    res.json({msg: 'Success'});
});
like image 131
Terry Lennox Avatar answered Jul 22 '26 04:07

Terry Lennox


The Access-Control-Allow-Origin header can be either:

  • * to allow from everywhere
  • A specific URL with / as the path

You cannot put a regular expression there.


You can apply your regular expression to the Origin header in the request and, if it matches, copy the value from the Origin request header to the Access-Control-Allow-Origin response header.

var origin = req.get("Origin");
if (origin && origin.match(your_regex)) {
    res.header("Access-Control-Allow-Origin", origin);
}

Or you can just use the CORS middleware which has a configuration option for this situation.

like image 21
Quentin Avatar answered Jul 22 '26 02:07

Quentin