我在 Rest API 的上下文中。当我执行跨域请求时,我需要发回标头“Access-Control-Allow-Origin”。
我有一个控制器,例如:
@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 发送请求,控制器将永远不会处理该请求:
$ 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
任何人都知道为什么我会收到这个“默认响应”以及为什么我不能自定义它?