cros要求取消要求

时间:2019-05-19 13:14:37

标签: angular spring-boot

我正在尝试使用Spring Boot和Angular 7创建一个应用程序,其中有2个按钮,一个显示列表,另一个具有允许用户添加到数据库的形式,第一个按钮可以正常工作,但是第二个不起作用我每次都会收到此消息

Access to XMLHttpRequest at 'http://localhost:8080/add' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这是代码正在使用: 这是我的Spring Boot应用程序的代码

 @RequestMapping("/showfpy")
    public List<fpy> index() {
        return (List<fpy>) fpyRepository.findAll();
    }

    @PostMapping("/add")
    public  List<fpy> Add(@RequestBody fpy fpy) {
        fpyRepository.save(fpy);
        return fpyRepository.findAll();
    }

这是我Angular项目中的代码

  fpy: FPY;
      constructor(private  route: ActivatedRoute, private router: Router, private  fpyservice: FpyServiceService) {
        this.fpy = new FPY();
      }
    onSubmit() {
        console.log(this.fpy.produit + this.fpy.date + this.fpy.val_fpy);
        this.fpyservice.save(this.fpy).subscribe(result => this.gotofpylist());
    }
      ngOnInit() {
      }

      gotofpylist() {
        this.router.navigate(['/showfpy']);
      }

我将此部分添加到了我的mainApplication

@Bean
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registrationBean =
                new FilterRegistrationBean(new CORSFilter());
        registrationBean.setName("CORS Filter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;}
public class CORSFilter extends GenericFilterBean implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    //    httpResponse.setHeader("Access-Control-Allow-Methods", "*");
     httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

        httpResponse.setHeader("Access-Control-Allow-Headers", "*");
       httpResponse.setHeader("Access-Control-Allow-Headers",
               "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, Authorization");

        httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");

        System.out.println("********** CORS Configuration Completed **********");

        chain.doFilter(request, response);
    }


} // The End...

3 个答案:

答案 0 :(得分:2)

我设法解决了这个问题, 如果有人在这里寻找答案,那就是: 只需添加一个Java类并将其添加到其中即可:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

答案 1 :(得分:1)

我认为这两行相互重叠

httpResponse.setHeader("Access-Control-Allow-Headers", "*");
httpResponse.setHeader("Access-Control-Allow-Headers",
           "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token,      Authorization");

尝试删除第二个。

答案 2 :(得分:0)

您必须配置CORS配置。创建一个单独的类而不是MainClass

WebConfig.java

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      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-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type,"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    } 
}