I have recently built a new project which has react on the frontend and a node js server as the backend. The API calls worked on localhost with cors but when I published to vercel i keep running into the same error no matter how much i change my cors settings. If anyone knows how to fix this error:
Access to XMLHttpRequest at 'https://portfolio-5-0-backend.vercel.app/api/send-email' from origin 'https://portfolio-5-0-frontend.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cors settings:
const allowedOrigins = ["https://portfolio-5-0-frontend-2c3fpno4h-kroplewskims-projects.vercel.app", "https://portfolio-5-0-frontend.vercel.app"];
const corsOptions = {
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, { origin: true });
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Access-Control-Allow-Origin", "Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"],
credentials: false,
};
app.options("*", cors(corsOptions));
app.use(cors(corsOptions));
app.use(bodyParser.json());
react api call:
const onSubmit = handleSubmit(async (data) => {
try {
PushNotification("Sending email...", "bg-info");
const response = await axios.post("https://portfolio-5-0-backend.vercel.app/api/send-email", {
Email: data.Email,
Name: data.Name,
Message: data.Message,
}, {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
if (response.status === 200) {
PushNotification("Email sent successfully!...", "bg-success");
}
} catch (e) {
PushNotification("Failed to send email", "bg-error");
console.log(e);
}
});
The url that im trying to make the API call from is: https://portfolio-5-0-frontend.vercel.app/