簡體   English   中英

Spring Boot的CORS問題

[英]CORS issue with Spring Boot

我有一個在端口8443上運行的Spring Boot應用程序,在端口8080上有一個基於angular2的前端。我需要我的前端向我的Spring服務器發出請求,但是我左右收到CORS錯誤。 我已經將@CrossOrigin注釋添加到我的RestController方法中,並且已經將CORSFilter添加到我的項目中,並將其映射到web.xml ,但是在Firefox 46.0a2上,我仍然在控制台上收到此錯誤:

跨源請求已阻止: 同源策略禁止在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:

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() {}
}

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>

我不知道這是否重要,但是正在發出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);
    }
}

我錯過了一些配置嗎? 我的代碼有什么不對嗎?

編輯:我放棄並從之前的提交重新啟動。 在那之后,簡單地添加@Cross-Origin就足夠了。

第一種方法: -如果您使用的是spring boot,則創建一個擴展webmvcconfigurereAdapter的新類

 @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。 originheadersmethods等都可以根據您的需要進行配置。

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

我很確定您需要在允許的標頭中添加Content-Type

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

這是我在項目中工作的內容:

@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或屬性文件配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM