8

I want to allow cross origin requests for one domain. My project uses Spring so I want to take advantage of the new CORS support.

I am using version 4.2.0 for all springframework dependencies.

I followed the example here https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#disqus_thread and tried the first version. My controller annotations looks like:

@CrossOrigin(origins = "http://fiddle.jshell.net/", maxAge = 3600)
@Controller
@RequestMapping("/rest")
public class MyController 

If I understood correctly the mvc-config is an alternative method. I tried it as well:

<mvc:cors>  
    <mvc:mapping path="/**"
        allowed-origins="http://fiddle.jshell.net/, http://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="false"
        max-age="123" />    
</mvc:cors>

With either methods, the Response doesn't seem to contain anything like Access-Control-Allow-Origin, neither can I get a result back through a simple query from jsfiddle.

The header info from Chrome developer tools, when ran and accessed from localhost is below. In this case the request is from the same domain and not through javascript, but I thought the CORS annotation would add the access control parameters anyway?

Response Headers:

Content-Length:174869 
Content-Type:text/html;charset=UTF-8 
Date:Fri, 21 Aug 2015 12:21:09 GMT 
Server:Apache-Coyote/1.1

Request Header:

      Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*\/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ro;q=0.6,de;q=0.4,fr;q=0.2
Cache-Control:no-cache 
Connection:keep-alive
Cookie:JSESSIONID=831EBC138D2B7E176DF4945ADA05CAC1;_ga=GA1.1.1046500342.1404228238; undefined=0 
Host:localhost:8080 
Pragma:no-cache 
Upgrade-Insecure-Requests:1 
User-Agent:Mozilla/5.0(Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36

I do not use spring boot and I presume I missed a configuration step.

4

2 回答 2

3

我已经为自己重现了这个问题。当我的 @Configuration 注释类中没有 @EnableWebMvc 注释时,就会出现问题。我已将此问题报告为 Sping Jira 中的一个错误,其中包含详细信息:https ://jira.spring.io/browse/SPR-13857

我在代码或文档中看到了修复。文档修复将在 @CrossOrigin 类 javadoc 中声明需要 @EnableWebMvc,但我更喜欢代码中的修复,以便 cors 注释在没有 @EnableWebMvc 的情况下工作。

于 2016-01-11T15:06:59.800 回答
0

您可以尝试使用"http://fiddle.jshell.net"而不是"http://fiddle.jshell.net/"吗?

于 2015-08-21T15:28:24.303 回答