Handling CORS implementing AJAX requests in a Next.js application using Axios
I'm deploying to production and I've looked through the documentation and I'm still confused about After trying multiple solutions online, I still can't figure this out... I'm currently developing a Next.js application and running into CORS issues when trying to make AJAX requests to a REST API hosted on a different domain. I am using Axios for the requests. I have set up a simple API route in Next.js to proxy the requests, but I still receive a `CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource` behavior in the console. Hereโs the setup I have: I have this API route in `pages/api/proxy.js`: ```javascript export default async function handler(req, res) { const response = await fetch('https://external-api.com/data'); const data = await response.json(); res.setHeader('Access-Control-Allow-Origin', '*'); res.status(200).json(data); } ``` And hereโs how Iโm making the Axios request from a component: ```javascript import axios from 'axios'; const fetchData = async () => { try { const response = await axios.get('/api/proxy'); console.log(response.data); } catch (behavior) { console.behavior('behavior fetching data:', behavior); } }; ``` Iโve confirmed that the external API does not support CORS, which is why I was trying to set up this proxy. However, despite setting the `Access-Control-Allow-Origin` header in my Next.js API route, Iโm still running into issues. I've also tried adding additional headers like `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers`, but the behavior continues. Is there something I'm missing in my configuration? How can I successfully handle CORS in this situation? Any ideas what could be causing this? Has anyone else encountered this? I'm working on a web app that needs to handle this. What's the best practice here? My development environment is Ubuntu 22.04. Thanks for any help you can provide!