Recently, I have been testing different methods to avoid a CORS error in my upcoming app deployed on Vercel. The only solution that worked for me was manually setting the headers for each API request, as shown below:
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET')
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
)
// Handling pre-flight requests
if (req.method === 'OPTIONS') {
res.status(200).end()
return
}
let houses: House[] = []
try {
await client.connect()
console.log('Successfully connected to MongoDB')
const db = client.db('vroom')
const housesCollection = db.collection('houses')
houses = (await housesCollection.find().toArray()).map((house) => ({
house: house.house,
price: house.price,
timestamp: house.timestamp,
developer: house.developer,
}))
console.log('Retrieved houses:', houses)
} catch (error) {
console.error(`Error while connecting to MongoDB: ${error}`)
} finally {
await client.close()
}
res.json({ houses })
}
Is there a way to achieve the same outcome using the middleware.ts file or by implementing wrapper code? I would appreciate any guidance on this matter.
Feel free to ask for clarification if needed!
Thank you!
I attempted the above steps but had to include some text here :)