If you are developing an Angular app which is connecting to an API which is also running on your localhost, you have probably started seeing error messages like this:
access to XMLHttpRequest at 'localhost:5000/myapi/' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.....
Because the client and the server are both running on the same domain we have to implement a server side proxy to resolve the CORS issue.
In my error message, my server api is at http://localhost:5000/myapi. My client is running http://localhost:4200. By implementing a proxy we essentially enable http://localhost:4200/myapi to pass through to http://localhost:5000/myapi.
Create a new file called proxy.conf.json at the same level as your package.json file.
Add the following contents but adapted for your API.
{
"myapi": {
"target": "http://localhost:5000",
"secure": false,
"logLevel": "debug"
}
}
Edit your package.json file to change the npm start process to serve via your new proxy file. E.g. My scripts section looks like this:
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}
Now to start your application, run:
npm start
You should now be able to make requests to "/myapi" from your Angular app.