I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.
I used version 7.2.15 of angular in my project.
when get this url with httpClient throw following error :
Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
While at work correctly when enter url in browser and postman.
why ?
Use a Chrome extension to add Access-Control-Allow-Origin header into every response. To find one of them, just head over to Chrome Webstore and type in "CORS", dozens will show up in the search result. Or you can install CORS Helper, CORS Unblock or dyna CORS right away.
< access-control-allow-origin: * You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it! Thanks this helps to avoid all the hassle and test the code from localhost.
Solution 1 - you need to change your backend to accept your incoming requests
Solution 2 - using Angular proxy see here
Please note this is only for
ng serve
, you can't use proxy inng build
Solution 3 - IF your backend accepts requests from a wildcard domanin like *.mydomain.example
then you can edit your hosts
file and add 127.0.0.1 local.mydomain.example
in there, then in your browser instead of localhost:4200
enter local.mydomain.example:4200
Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.
I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them
What i mean is:
change this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
...
}
to this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
...
}
By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.
if You use spring boot , you should add origin link in the @CrossOrigin annotation
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")
You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With