admin管理员组

文章数量:1193778

I am using Express and the cors library to build a REST API. This API has been in production for several weeks, and some CORS issues have started to appear. I have configured my CORS settings to allow only one domain and one subdomain, which correspond to the origins of my website and its back office.

Sometimes, a route that worked perfectly just a few minutes earlier suddenly triggers a CORS error. The route remains inaccessible until the browser inspector is opened and the "Disable cache" option is checked.

This issue affects all browsers. Refreshing the page while clearing the cache (CTRL + SHIFT + R) does not resolve the problem, and neither does closing and reopening the tab.

Here is my app configuration:

app.use(
    cors({
        origin: (origin, callback) => {
            logger.error(origin);
            if (!origin) {
                logger.error("Origin is null");
                return callback(null, true);
            }
            logger.error("Testing the origin");
            var re = new RegExp(process.env.CLIENT_URL);
            logger.error(re.test(origin));
            if (re.test(origin) === false) {
                logger.error("Origin is not allowed");
                const corsError = new Error("CORS policy: This origin is not allowed.", false);
                corsError.status = 401;
                return callback(corsError, false);
            }
            logger.error("Origin is allowed");
        },
        credentials: true,
        allowedHeaders: ["sessionId", "Content-Type", "authorization"],
        exposedHeaders: ["sessionId"],
        methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
        preflightContinue: false,
    })
);

I already confirm many times that my regexp is fine.

When a route triggers an error, my logger shows that the origin is "undefined," which is surprising cause the same route had an origin before.

I have no idea where the problem could be coming from at this point, and I’m relying on your help to resolve it. Don't hesitate to ask me for further informations like screenshots or logs.

本文标签: expressExpressJs and CORS errors on subdomainsStack Overflow