I have a React application created using Nx and there I'm trying to make api calls to my dev server but getting CORS issues. So I tried setting up a proxy following this link: https://nx.dev/l/r/tutorial/06-proxy#react-nx-tutorial---step-6-proxy-configuration
Inside my project's server, I've added:
workspace.json or project.json
"serve": {
"executor": "@nrwl/web:dev-server",
"options": {
"buildTarget": "my-app:build",
"hmr": true,
"proxyConfig": "apps/my-app/proxy.conf.json"
},
And proxy.conf.json:
{
"/my-context-path/api/v1": {
"target": "https://my-dev-server.com",
"secure": true
}
}
And making api call as:
export async function getInfo(planId, nbr) {
return await fetch(`/my-context-path/api/v1/getInfo?planId=${planId}&nbr=${nbr}`, {
method: 'GET',
headers: {
'Authorization': 'Basic authHeader',
'Content-Type': 'text/plain',// adding or removing this header is making no difference
}
}).then(async (response) => {
// success block
}).catch(async (error) => {
// failure block
})
}
The issue is that when I set up proxy, I'm getting 404 not found error. And if I directly hit the server without using proxy, I'm getting CORS issue.
Url being called is: https://localhost:4200/my-context-path/api/v1/getInfo?planId=<...data>&irsNbr=<...data>
Note: Cors has already been enabled in the backend server.
Can someone help me fix this issue or point out what I am missing or doing wrong?
UPDATE : Found a solution! I added "changeOrigin": true in my proxy.conf.json and restarted my system then it started to work fine. But I still don't understand why restarting the system made it work. May be some sort of cache issue, which I'm still not clear about.
proxy.conf.json - updated
{
"/my-context-path/api/v1": {
"target": "https://my-dev-server.com",
"secure": true,
"changeOrigin": true
}
}