JHipster spring boot 接口解决跨域问题

Jhipster默认对跨域的支持

 

但是要怎么用,还是看你了....

 

什么是跨域

浏览器的同源策略导致了跨域.

同源策略限制了从同一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。

 

为什么要跨域

简单的一点说明就是,不同的服务器之间进行接口调用.

 

如何跨域

 

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)跨域资源共享 CORS 详解。看名字就知道这是处理跨域问题的标准做法。CORS有两种请求,简单请求和非简单请求。\

 

 

JHipster的跨域解决方案:

 

JHipster中给的配置文件为:

jhipster:
    http:
        version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration)
    # CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
    cors:
        allowed-origins: "*"
        allowed-methods: GET, PUT, POST, DELETE, OPTIONS
        allowed-headers: "*"
        exposed-headers:
        allow-credentials: true
        max-age: 1800

 

使用注入bean的方式,来进行对url path的拦截

 

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = jHipsterProperties.getCors();
        if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
            log.debug("Registering CORS filter");
            source.registerCorsConfiguration("/**", config);
            source.registerCorsConfiguration("/v2/api-docs", config);
        }
        return new CorsFilter(source);
    }

cors中对需要传入的是path路径...

这里就是有个坑....

 

使用原生的JHipster的构建的框架中.register拦截的路径是/api/**,即/api下所有的目录及子目录,而我们在写接口的时候,接口名称是不会添加/api,而是直接写简单的业务名称来区分不同的接口名称,这也就是说.我们注册拦截的需要进行跨域的是/api/**下所有的接口,而我们写的接口不在这个目录下面,所以就会出现接口不满足跨域的问题...

 

改为/**后就是对所有的接口路径进行拦截....

 

TIPS

/** 的意思是所有文件夹及里面的子文件夹

/*  是所有文件夹,不含子文件夹(如果在某个请求下的子文件夹请求就不会拦截,很多ajax都不会被拦截)

/   是web项目的根目录

 

如果我们只需要对某个特定的接口名称进行跨域操作,只需要更改path的这个匹配路径即可....

如/api/cors/*    只允许有三层,且前两层是/api/cors

/api/cors/**      至少有三层,且前两层是/api/cors

 

 

如果是简单的springmvc项目(springboot或者ssm等框架的)

1,可以通过直接注入cors的configuration来实现

 

package com.trs.idap.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by Administrator on 2019/2/12.
 * 描述:
 *
 * @author Young
 * @create 2019-02-12 15:58
 */
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
            .maxAge(3600);
    }
}

 

2,可以在方法上或者类上直接添加注解

@CrossOrigin(origins = "*", maxAge = 3600)

实现跨域操作

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章