我有一个reactjs前端,它基于spring集成向我的api发送一个请求。
我得到的问题是,我不知道如何在我的网关中绑定CORS功能。
我试过这样的东西
@Bean
public CrossOrigin cors(){
CrossOrigin c = new CrossOrigin();
c.setOrigin("/**");
return c;
}@Bean
public IntegrationFlow httpGetTest() {
return IntegrationFlows.from(httpGetGateTest()).channel("http.test.channel").handle("testEndpoint", "hello").get();
}@Bean
public MessagingGatewaySupport httpGetGateTest() {
HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();
handler.setRequestMapping(createMapping(new HttpMethod[]{HttpMethod.GET}, "/test"));
handler.setCrossOrigin(cors());
handler.setHeaderMapper(headerMapper());
return handler;
}请求:
axios.get('http://localhost:8080/test')
.then(res=>{console.log(res)})我的端点返回"Hello World“
Failed to load resource: the server responded with a status of 415 ()Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.发布于 2019-06-29 22:58:24
首先,请确保您的客户端确实发送了一个Origin HTTP请求头。否则CORS过滤将不会应用于请求:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
尽管它听起来像是存在的:from origin 'http://localhost:3000'。
考虑将您的setOrigin("/**")更改为setOrigin("*")。跨域策略是关于整个ULR (准确地说是域名),而不是相对路径。
顺便说一句,Spring Integration for HTTP components中有一个Java DSL工厂:
@Bean
public IntegrationFlow httpGetTest() {
return IntegrationFlows.from(Http.inboundGateway("/test")
.requestMapping(r -> r.methods(HttpMethod.GET))
.crossOrigin(cors -> cors.origin("*"))
.headerMapper(headerMapper()))
.channel("http.test.channel")
.handle("testEndpoint", "hello")
.get();
}https://stackoverflow.com/questions/56817745
复制相似问题