Angular HttpClient doesn't send POST, it sends OPTIONS
It is not angular related, it is your browser doing.
Check this issue.
I assume your server runs at localhost:8080, and your angular application at localhost:4200. Since, your request is a cross origin request, browser first sends an OPTIONS
request to see if it is safe. At this point, your server returns a response with http code 401 which prevents the post request from being made.
Either you have to do some config in your server or you can use webpack proxy. This is just for your local machine. If you serve your bundled angular application from your server, then you won’t have to do anything for production. I’ve been using this technique for quite some time, and it works just fine.
Example,
Users access my angular application from mydomain.com/ng-app I also serve my rest api from same domain, mydomain.com/api
So my application always make the request to the server it’s being served from which causes no problem in production.
For latter, you can do following
Create a proxy.conf.json
at the root of your project (next to package.json
)
And put following inside
{
"/api/": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin": true
}
}
In package.json, edit your start
script and make it ng serve --proxy-config proxy.conf.json
Also, from your frontend, do not send the requests to localhost:8080 directly, instead just write something like http.post('/api/getSomeData')
which will make the request to localhost:4200 which will redirect it to localhost:8080. This way, you won't have to deal with CORS.