Psuedodoro
Psuedodoro

Reputation: 303

ExpressJS Multi-Server CORS issue

I have a frontend server (using VueJS) that is hosted on Vercel, and then I have my backend as a service worker using HerokuApp. Now they both use the same custom domain (maev.me), but I would like to have a CORS rule so I can make it so that requests can only be sent from a domain/subdomain to the api.

The api is on one server, on the URL api.maev.me, and the frontend is on just the normal URL maev.me.

Is there any way to try and setup an ExpressJS CORS rule? I have tried using this regex I made:
^.+\.+maev\.me$

But that still doesn't work and spits out the error:

[Error] Origin https://www.example.me is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load https://api.example.me/me due to access control checks.
[Error] Failed to load resource: Origin https://www.example.me is not allowed by Access-Control-Allow-Origin. (me, line 0)

All help is appreciated.

Upvotes: 0

Views: 190

Answers (1)

Phil
Phil

Reputation: 164730

The problem with your regex is that it doesn't match https://maev.me because of the literal .

Try using an array of mixed string literal and regex

app.use(cors({
  origin: ["https://maev.me", /^https:\/\/.+\.maev\.me$/]
}))

Keep in mind that CORS is not access control. This won't prevent non-browser clients from accessing your API.


After your update, I checked your API via curl and everything seems correct as far as CORS headers go

curl -X OPTIONS -H "Origin: https://maev.me" "https://api.maev.me/"

< Access-Control-Allow-Origin: https://maev.me

curl -X OPTIONS -H "Origin: https://foobar.maev.me" "https://api.maev.me/"

< Access-Control-Allow-Origin: https://foobar.maev.me

curl -X OPTIONS -H "Origin: https://example.com" "https://api.maev.me/"

[no access-control-allow-origin]

Any other errors are not related to your CORS configuration

Upvotes: 1

Related Questions