Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS Angular and SpringBoot - request blocked

I have a problem that I don't seem to figure out. I want to send a http request from my

Angular client:

const url = 'http://localhost:8080/api';
console.log(this.http.get(url).subscribe(data => this.greeting = data));

to SpringBoot backend where I use CORS annotation:

@CrossOrigin(origins = "http://localhost:4200/", maxAge = 3600)
    @RequestMapping("/api/")
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

but I'm getting an error that it's blocked and redirects me to login all the time.

Failed to load http://localhost:8080/api: Redirect from 'http://localhost:8080/api' to 'http://localhost:8080/login' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 

Is there a way to change that?

I appreciate any hint or help regarding this. I would like to understand why this problem is happening.

like image 202
Maciej Czarnota Avatar asked Apr 03 '18 00:04

Maciej Czarnota


People also ask

How do you solve the CORS problem in spring boot?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

What is@ CrossOrigin annotation?

This @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.


2 Answers

You have error in your RequestMapping, as you have used @RequestMapping("/api/"), this will be evaluated as http://your_url/api//. Such mapping is not present in your controller, hence it is giving you CORS Origin error.

Just remove trailing / from @RequestMapping("/api/") so that it will be @RequestMapping("/api").

Your class should look like follows,

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class DemoController {

    @RequestMapping(value = "/api", method = RequestMethod.GET)
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }
}
like image 131
Plochie Avatar answered Nov 23 '22 10:11

Plochie


This is the problem with your server-side. all you will have to do is do a component in your server-side and it will solve the issue. or refer here

follow this code:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
            try {
                chain.doFilter(req, res);
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Pre-flight");
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "authorization, content-type," +
                    "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
            response.setStatus(HttpServletResponse.SC_OK);
        }

    }
    }
like image 33
Abhishek Ekaanth Avatar answered Nov 23 '22 12:11

Abhishek Ekaanth