【问题标题】:Error CORS Spring + Angular 5 + Jasperreport错误CORS Spring + Angular 5 + Jasperreport
【发布时间】:2018-03-15 23:04:30
【问题描述】:

那是我的班级休息控制器:

@RestController
@RequestMapping("/adiantamento-api/adiantamento")
@CrossOrigin(origins = "http://localhost:4200")
public class RelatorioController {
     .....
   }

这是我生成报告的方法,在 RelatorioController 里面

@RequestMapping(path="gerar-relatorio/", method = RequestMethod.GET)    
    public void gerarRelatorio(HttpServletResponse response) throws Exception {

        try {



            String nomeRelatorio = "RelAdvertenciaDB";//JsonUtils.getProperty(parametros, "nome_relatorio", "x", String.class);
            Map<String, Object> reportParameters = new HashMap<>();

            DatabaseContextHolder.set(DatabaseEnvironment.CICLOCAIRU);


            reportParameters.put("CODIGO", 880);            
            InputStream reportStream = new  ClassPathResource("relatorios/" + nomeRelatorio + ".jrxml").getInputStream();


            JasperReport jasper =  JasperCompileManager.compileReport(reportStream);
            JRSaver.saveObject(jasper, "report.jasper");

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParameters, jdbctemplate.getDataSource().getConnection());

            JRPdfExporter exporter = new JRPdfExporter();                       

            exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
            exporter.setExporterOutput(
              new SimpleOutputStreamExporterOutput("src\\main\\resources\\relatorios\\gerados\\"+nomeRelatorio+".pdf"));

            SimplePdfReportConfiguration reportConfig
              = new SimplePdfReportConfiguration();
            reportConfig.setSizePageToContent(true);
            reportConfig.setForceLineBreakPolicy(false);

            SimplePdfExporterConfiguration exportConfig
              = new SimplePdfExporterConfiguration();
            exportConfig.setMetadataAuthor("JETERSON");             

            exporter.setConfiguration(reportConfig);
            exporter.setConfiguration(exportConfig);

            exporter.exportReport();


            File file = new File("src\\main\\resources\\relatorios\\gerados\\"+nomeRelatorio+".pdf");
            try(InputStream is = new FileInputStream(file);OutputStream out = response.getOutputStream()){
                response.reset();
                response.setContentType("application/pdf");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment; filename="+nomeRelatorio+".pdf");
                IOUtils.copy(is, out);
                out.flush();
            }


        }catch (Exception e) {
            throw new Exception(e);
        }
    }

我的 Cors 过滤器

@Configuration
@EnableWebMvc
public class WebConfigCors extends WebMvcConfigurerAdapter {

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

我不知道这是否重要,但这是我的身份验证类别

public class TokenAuthenticationService {

    // EXPIRATION_TIME = 10 dias
    static final long EXPIRATION_TIME = 860_000_000;
    static final String SECRET = "MySecret";
    static final String TOKEN_PREFIX = "Bearer";
    static final String HEADER_STRING = "Authorization";

    static void addAuthentication(HttpServletResponse response, String username) {
        String JWT = Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        response.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", HEADER_STRING);
    }

    static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);

        if (token != null) {
            // faz parse do token
            String user = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
            }
        }
        return null;
    }

}

该项目有许多客户端 Angular 请求的控制器,但只有我的类 RelatorioController 抛出错误 cors,当生成 report Jasper 我在浏览器中收到错误 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

我怀疑这是因为jasper reposrts 它尽管毫无意义 如果我评论所有负责生成报告的行代码,则请求有效

编辑:这是我的角度调用

emitirAdvertencia(parametros: Object): any {
        parametros['dbenv'] = ApplicationContext.getInstance().getDbenv();
        parametros['usuario'] = ApplicationContext.getInstance().getUser().codigoUsuario;
        parametros['nome_relatorio'] = 'RelAdvertenciaDB';
        var httpOptions = {

            headers: new HttpHeaders({
                'Content-Type': 'application/pdf',
                'Authorization': this.localStorage.get('token'),
                // all others methods not need this
                'Access-Control-Allow-Origin': '*'
            }),
            responseType: 'blob' as 'blob',
        };        
        return this.http.get(ApplicationContext.URL + '/adiantamento/gerar-relatorio/', httpOptions)
            .map((res) => {
                return new Blob([res], { type: 'application/pdf' });
            });
    }

【问题讨论】:

    标签: angular spring-mvc spring-boot jasper-reports


    【解决方案1】:

    如果我没记错的话,当客户端提供凭据时,Access-Control-Allow-Origin 标头上的通配符 ('*') 不可用。提供凭据时,允许的来源需要具体。

    所以,你可以尝试改变

    response.addHeader("Access-Control-Allow-Origin", "*");
    

    response.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    

    【讨论】:

    • 感谢您的回复,我按照建议修改了它,但它仍然不起作用,我在问题中编辑并添加了我的角度代码
    • 我发现了。 Precisa adicionar Cors em HttpServletResponse no meu controlador response.addHeader (" Access-Control-Allow-Origin "," * ");
    猜你喜欢
    • 2021-11-09
    • 2021-07-13
    • 2020-02-02
    • 2020-11-05
    • 2018-07-22
    • 2019-08-25
    • 2020-02-07
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多