Problem with CORS

Asked

Viewed 614 times

1

I’m making a request through the Angularjs at port 3000:

function _registrarNovaAposta(aposta) {return $http.post("http://localhost:8080/sga-api/apostas/nova-aposta", aposta);}

to the endpoint:

@POST
@Path("/nova-aposta")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String registrarNovaAposta(Aposta aposta) {
    apostaService.registrar(aposta);
    return "ok";
}

but I get the following error on the console: "Access to Xmlhttprequest at 'http://localhost:8080/sga-api/bets/new bet' from origin 'http://localhost:3000' 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."

the problem is that GET returns the data normally, but with the POST of this CORS problem, I tried to configure the "headers" in $http.post but it didn’t work.

I am using the Tomcat 9 server in the back-end

1 answer

1

You can configure filters for Cors policy on the Tomcat web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

there are some advanced settings in documentation.

Or you can configure Cors filters directly in java like this example

package com.yourdomain.package;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter 
{

   @Override
   public void filter(final ContainerRequestContext requestContext,finalContainerResponseContext cres) throws IOException 
    {
      cres.getHeaders().add("Access-Control-Allow-Origin", "*");
      cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
      cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
      cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      cres.getHeaders().add("Access-Control-Max-Age", "1209600");
   }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.