I am working on a chat application with Django at the back-end and React at the front-end. Both are hosted on separate domains on vercel.
I have added the CORS configurations in the back-end but they don't seem to be working in the production.
Following are the CORS configs done in Django:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ALLOWED_HOSTS = ['.vercel.app']
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['https://texter-frontend.vercel.app',]
Here is one of the requests from the front-end:
const backendServerEndpoint = 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app';
const requestData = {
'phoneNumber' : phoneNumber
};
fetch(backendServerEndpoint + '/auth/sendotp/',{
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
credentials: 'include',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
})
.then(
response => {
if(response.status === 200){
setOtpSent(true);
response.json()
.then(
responseData => {
console.log(responseData);
if(responseData.newProfile){
console.log("It is a new profile!!!");
setNewProfile(true);
}
}
)
}
}
)
.catch(
error => {
console.log(error);
}
)
This is the error that I am getting in the console:
Access to fetch at 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app/auth/sendotp/' from origin 'https://texter-frontend.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
P.S: When I deploy it on my local by replacing the vercel URLs with localhost/127.0.0.1, it is working fine.
https://github.com/sourav-py/texter_backend https://github.com/sourav-py/texter_frontend
Thank you.