2016-03-22 21 views
3

私はSpringブートアプリケーションをポート8443上で実行しており、angle2ベースのフロントエンドはポート8080上で動作させています。私のフロントエンドはSpringサーバに要求する必要がありますが、そして右。私は私のRestControllerメソッドに@CrossOrigin注釈を追加した、と私は私のプロジェクトにCORSFilterを追加した、とweb.xml上にマッピングされますが、Firefoxの46.0a2に私はまだコンソールにこのエラーを取得する:CORSのSpringブートでの問題

クロスオリジンリクエストがブロックされました:同じオリジンポリシーにより、リモートリソース をhttps://localhost:8443/allEquipsに読み込むことができません。 (理由:CORS ヘッダー 'Access-Control-Allow-Origin'がありません)。

私のコントローラの関連部分:

@CrossOrigin 
@RequestMapping("/allequips") 
List<String> allequips(Model model) { 
    List<String> codes = equipmentRepository.findAllEquipments(); 
    return codes; 
} 

CORSFilter:web.xml

public class CORSFilter implements Filter{ 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
      HttpServletResponse response = (HttpServletResponse) res; 
      response.setHeader("Access-Control-Allow-Origin", "*"); 
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 
      response.setHeader("Access-Control-Max-Age", "3600"); 
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
      chain.doFilter(req, res); 
     } 
     public void init(FilterConfig filterConfig) {} 
     public void destroy() {} 
} 

マッピング:

<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> 

そして、この場合、私は知りません重要ですが、httを作成しているAngular2コードpリクエスト:

@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); 
    } 
} 

いくつかの設定がありません。私のコードはどうやって間違っていますか?

EDIT:私は前のコミットからあきらめて再開しました。その後、単に@Cross-Originを追加するだけで十分でした。

答えて

0

私はあなたが許可され、ヘッダー

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

最初のアプローチでContent-Typeを追加する必要があります確信している: - その後、webmvcconfigurereAdapter

@Configuration 
@ComponentScan 
@EnableWebMvc 

public class ApplicationConfig extends WebMvcConfigurerAdapter { 

    @Override 
- public void addCorsMappings(CorsRegistry registry) { 
-  registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST"); 
- } 
} 
を拡張する新しいクラスを作成するには、春のブートを使用している場合

2番目のアプローチ: - また、これを@springBootApplication cラス。 xmlは必要ありません。

@Bean 
    public CorsFilter corsFilter() { 
     final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     final CorsConfiguration config = new CorsConfiguration(); 
     config.setAllowCredentials(true); 
     config.addAllowedOrigin("*"); 
     config.addAllowedHeader("*"); 
     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); 
    } 
0

ここで私は私のプロジェクトで働いてきたものだ:

@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またはプロパティファイルから構成され、あなたができるようにしたい起源の一覧です。

関連する問題