我在 Rest API 的上下文中。当我执行跨域请求时,我需要发回 header “Access-Control-Allow-Origin”。
我有一个 Controller ,例如:
@Controller
@RequestMapping("/api")
public class PackageManagerRestController {
@RequestMapping(method = RequestMethod.OPTIONS, value = "/test")
public void commonOptions(HttpServletResponse theHttpServletResponse) throws IOException {
theHttpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
theHttpServletResponse.addHeader("Access-Control-Max-Age", "60"); // seconds to cache preflight request --> less OPTIONS traffic
theHttpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
theHttpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
}
@RequestMapping(method = RequestMethod.GET, value = "/test")
public void getPtions(HttpServletResponse theHttpServletResponse) throws IOException {
theHttpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
theHttpServletResponse.addHeader("Access-Control-Max-Age", "60"); // seconds to cache preflight request --> less OPTIONS traffic
theHttpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
theHttpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
}
}
如果我使用 GET 运行测试,结果如预期:
$ curl -i -X GET http://localhost:8081/api/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Headers: origin, content-type, accept, x-requested-with
Access-Control-Max-Age: 60
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
Content-Length: 0
Date: Wed, 16 Apr 2014 08:18:38 GMT
但是,如果我使用 OPTIONS 发送请求,则 Controller 永远不会处理该请求:
$ curl -i -X OPTIONS http://localhost:8081/api/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Wed, 16 Apr 2014 08:19:56 GMT
任何人都知道为什么我会收到这个“默认响应”以及为什么我不能自定义它?
最佳答案
对于默认 Spring DispatcherServlet 仅支持 GET、HEAD、POST、PUT、PATCH 和 DELETE;如果您想支持 TRACE 和 OPTIONS,您必须将“dispatchOptionsRequest”和“dispatchTraceRequest”属性设置为“true”;在这里检查 docs.spring.io/spring/docs/4.0.3.RELEASE/javadoc-api
为了在你的 web.xml 中也支持 OPTIONS 你必须把这个:
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
通过添加它,我可以处理选项:
~$ curl -i -X OPTIONS http://localhost:8180/sample/api/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Headers: origin, content-type, accept, x-requested-with
Access-Control-Max-Age: 60
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Wed, 16 Apr 2014 08:44:55 GMT
安杰洛
关于Spring MVC 不处理 RequestMethod.OPTIONS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23103832/