I have a Node.js(v20.10.0
) backend server using Fastify(v4.26.2
) as the framework.
I have index.js as an entry point.
import Fastify, { FastifyInstance, FastifyServerOptions } from 'fastify';
import cors from '@fastify/cors';
// Assuming other settings and configurations already written.
fastify.register(cors, {
origin: "https://dev.example.com",
credentials: true,
});
I have a GET
API called for listing users https://api-dev.example.com/api/v1/users
which is working fine.
But the issue is coming with POST
API, where I can create user https://api-dev.example.com/api/v1/create-user
.
When using any POST
API, I am getting CORS Error
Access to XMLHttpRequest at ‘https://api-dev.example.com/api/v1/users’ from origin ‘https://dev.example.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests
Tried multiple approaches and still got the same error.
fastify.register(cors, {
origin: "*",
credentials: true,
});
By the error, I can understand that the OPTION
request is getting
in response headers Access-Control-Allow-Origin: *
that’s why I am getting this error.
But in all GET
API response headers Access-Control-Allow-Origin: https://dev.example.com
I am not sure why the OPTION
request before the POST
request Access-Control-Allow-Origin
is *