I’m developing a react web app using axios and the back and using nodejs.
However, when trying to access the API I get the following error:
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 initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
EVEN THOUGH I’M NOT USING THE WILDCARD AS THE FOLLOWING CODES PROVES:
Front End code:
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_BACK_END_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json;charset=UTF-8;multipart/form-data',
},
});
axiosInstance.interceptors.response.use(
(response) => response,
(error) =>
Promise.reject(
(error.response && error.response.data) || 'Something went wrong',
),
);
axiosInstance.AxiosHeaders = {
'Access-Control-Allow-Origin': import.meta.env.BACK_END_URL,
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE',
};
export default axiosInstance;
Back end code:
const app = express();
const corsOptions = {
origin: 'HERE IS THE FRONT END URL(CHANGED JUST TO POST THE QUESTION FOR PRIVACY REASONS)',
methods: ['GET', 'PATCH', 'POST', 'DELETE', 'PUT'],
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors({ corsOptions }));
app.options('HERE IS THE FRONT END URL(CHANGED JUST TO POST THE QUESTION FOR PRIVACY REASONS)', cors(corsOptions));
app.use(helmet());
What Am I doing wrong? I tried a lot of stack overflow solutions, but none have worked. Please wait till my answer to mark as duplicated, because I believe its not(since the others questions does not solutioned this erro). Thanks!
user25777499 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.