Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 弹簧靴的CORS问题_Spring_Firefox_Spring Boot_Cors_Angular - Fatal编程技术网

Spring 弹簧靴的CORS问题

Spring 弹簧靴的CORS问题,spring,firefox,spring-boot,cors,angular,Spring,Firefox,Spring Boot,Cors,Angular,我有一个在8443端口上运行的Spring Boot应用程序,还有一个在8080端口上运行的基于angular2的前端。我需要我的前端向我的Spring服务器发出请求,但我左右都会收到CORS错误。我已将@CrossOrigin注释添加到我的RestController方法中,并向我的项目中添加了一个CORSFilter,并将其映射到web.xml,但在Firefox 46.0a2上,我仍然在控制台上遇到此错误: 已阻止跨源请求:同一源策略不允许读取 位于的远程资源。(理由:CORS 缺少标题“

我有一个在8443端口上运行的Spring Boot应用程序,还有一个在8080端口上运行的基于angular2的前端。我需要我的前端向我的Spring服务器发出请求,但我左右都会收到CORS错误。我已将
@CrossOrigin
注释添加到我的RestController方法中,并向我的项目中添加了一个CORSFilter,并将其映射到
web.xml
,但在Firefox 46.0a2上,我仍然在控制台上遇到此错误:

已阻止跨源请求:同一源策略不允许读取 位于的远程资源。(理由:CORS 缺少标题“访问控制允许原点”)

我的控制器的相关部分:

@CrossOrigin
@RequestMapping("/allequips")
List<String> allequips(Model model) {
    List<String> codes = equipmentRepository.findAllEquipments();
    return codes;
}
web.xml
上的映射:

  <filter>
  <filter-name>cors</filter-name>
  <filter-class>config.CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

科尔斯
config.CORSFilter
科尔斯
/*
我不知道这是否重要,但发出http请求的Angular2代码:

@Injectable()
export class EquipService {
    equips: Array<Equip>;

    constructor(public http: Http) {
        console.log('Equip service created.', http);
    }

    getEquips() {
        return this.http.get(WebServiceEndPoint+'allEquips')
        .map((responseData) => {
            return responseData.json();
        }).map((equips: Array<any>) => {
            let result: Array<Equip> = [];
            if(equips) {
                equips.forEach((equip) => {
                    result.push(new Equip(equip.code));
                });
            }
            return result;
        }).subscribe( res => this.equips = res);
    }
}
@Injectable()
出口级设备服务{
装备:阵列;
构造函数(公共http:http){
log('Equipment service created',http);
}
getEquips(){
返回此.http.get(WebServiceEndPoint+'allEquips')
.map((响应数据)=>{
返回responseData.json();
}).map((装备:阵列)=>{
让结果:数组=[];
如果(装备){
每辆车的装备((装备)=>{
结果.推送(新装备(装备代码));
});
}
返回结果;
}).subscribe(res=>this.equips=res);
}
}
我是否缺少一些配置?我的代码有什么错误吗


编辑:我放弃了,从上一次提交重新启动。在那之后,只需添加
@交叉源代码
就足够了。

我很确定您需要在允许的标题中添加
内容类型

response.setHeader("Access-Control-Allow-Headers", "x-requested-with x-uw-act-as");

第一种方法:- 如果您使用的是spring boot,那么创建一个扩展
WebMVCConfigureAdapter

 @Configuration
 @ComponentScan
 @EnableWebMvc

 public class ApplicationConfig extends WebMvcConfigurerAdapter {

     @Override
   public void addCorsMappings(CorsRegistry registry) {
   // Can just allow `methods` that you need.
   registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
    }
}
第二种方法:- 您还可以将其添加到
@SpringBootApplication
注释类中。不需要xml。
来源
标题
方法
等都可以根据您的需要进行配置

@Bean
     public CorsFilter corsFilter() {
         final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         final CorsConfiguration config = new CorsConfiguration();
         config.setAllowCredentials(true);
         config.addAllowedOrigin("*"); // this allows all origin
         config.addAllowedHeader("*"); // this allows all headers
         config.addAllowedMethod("OPTIONS");
         config.addAllowedMethod("HEAD");
         config.addAllowedMethod("GET");
         config.addAllowedMethod("PUT");
         config.addAllowedMethod("POST");
         config.addAllowedMethod("DELETE");
         config.addAllowedMethod("PATCH");
         source.registerCorsConfiguration("/**", config);
         return new CorsFilter(source);
     }

以下是我在项目中的工作内容:

@Component
public class CrossOriginRequestFilter implements Filter {

    //Configurable origin for CORS - default: * (all)
    @Value("${app.http.filter.cors.origin:*}")
    private String originList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)req;
        HttpServletResponse httpResponse = (HttpServletResponse) res;

        String origin = httpRequest.getHeader("Origin");
        if (origin == null) {
            //this is the case of mobile, where it sends null as Origin
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        } else if (origin != null && originList.contains(origin)) {
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            httpResponse.setHeader("Access-Control-Allow-Origin", "https://yourdomain.com");
        }
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With");

        chain.doFilter(req, httpResponse);
    }

    @Override
    public void destroy() {
    }
}
这里的originList是您希望允许的来源列表,它是从application.yml或属性文件配置的

@Component
public class CrossOriginRequestFilter implements Filter {

    //Configurable origin for CORS - default: * (all)
    @Value("${app.http.filter.cors.origin:*}")
    private String originList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)req;
        HttpServletResponse httpResponse = (HttpServletResponse) res;

        String origin = httpRequest.getHeader("Origin");
        if (origin == null) {
            //this is the case of mobile, where it sends null as Origin
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        } else if (origin != null && originList.contains(origin)) {
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            httpResponse.setHeader("Access-Control-Allow-Origin", "https://yourdomain.com");
        }
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With");

        chain.doFilter(req, httpResponse);
    }

    @Override
    public void destroy() {
    }
}