Dear Altruistic,
For the past six to seven hours, I have dedicated significant effort to resolving the ‘Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.’ error during deployment on Vercel. Both the client and server are hosted on Vercel. Notably, the dall-e-clone website functions perfectly on my local machine. However, upon deployment to Vercel, the client encounters difficulty fetching data from the server due to CORS policy constraints. I also configured my vercel.json to enable the CORS on Vercel, following Vercel’s documentation to address this. However, it is not effective. I would highly appreciate any assistance you can offer in resolving this matter.
Thank you in advance.
vercel.json
{
“version”: 2,
“builds”: [
{ “src”: “./index.js”, “use”: “@vercel/node” }
],
“routes”: [
{
“src”: “/api/v1/post”,
“methods”: [“GET”, “POST”, “PUT”, “DELETE”, “PATCH”, “OPTIONS”],
“headers”: {
“Access-Control-Allow-Origin”: “",
“Access-Control-Allow-Methods”: “GET, POST, PUT, DELETE, PATCH, OPTIONS”,
“Access-Control-Allow-Headers”: “Content-Type”
}
},
{
“src”: “/api/v1/dalle”,
“methods”: [“POST”, “OPTIONS”],
“headers”: {
“Access-Control-Allow-Origin”: "”,
“Access-Control-Allow-Methods”: “POST, OPTIONS”,
“Access-Control-Allow-Headers”: “Content-Type”
}
}
]
}
index.js
import * as dotenv from “dotenv”;
import express from “express”;
import connectDB from “./mongodb/connect.js”;
import dalleRoutes from “./routes/dalleRoutes.js”;
import postRoutes from “./routes/postRoutes.js”;
import cors from “cors”;
// Load environment variables
dotenv.config();
// Create an instance of the express application
const app = express();
// Configure express to parse JSON requests
app.use(express.json({ limit: “50mb” }));
// Use cors middleware to handle CORS
app.use(cors());
// API routes
app.use(“/api/v1/post”, postRoutes);
app.use(“/api/v1/dalle”, dalleRoutes);
// General routes
app.get(“/”, async (req, res) => {
res.send(“Hello from DALL-E Cloneaazzzzaaaa”);
});
// Handle OPTIONS requests
app.options(“*”, cors()); // Respond to preflight requests
// Connect to MongoDB
connectDB(process.env.MONGODB_URL);
// Start the server
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(Server is running on port http://localhost:${port}
);
});