当我遇到 CORS 问题时,我正在使用 emberjs 框架和 Grails 3.0 REST 应用程序。按照本文中的步骤http://www.greggbolinger.com/rendering-json-in-grails-for-ember-js/ 帮助我走得更远。
本文展示了如何使用新的拦截器来创建设置正确标头的 CorsInterceptor 类。
class CorsInterceptor {
CorsInterceptor() {
matchAll()
}
boolean before() {
header( "Access-Control-Allow-Origin", "http://localhost:4200" )
header( "Access-Control-Allow-Credentials", "true" )
header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
header( "Access-Control-Max-Age", "3600" )
true
}
boolean after() { true }
}
这对 GET 请求按预期工作,但对 POST 和 PUT 请求失败。原因是 OPTIONS 预检请求首先发送到 http://localhost:8080/mycontroller/1234,在我的情况下,这导致返回 404 未找到。
在这个答案https://stackoverflow.com/a/31834551 的帮助下,我改为将 CorsInterceptor 类修改为:
class CorsInterceptor {
CorsInterceptor() {
matchAll()
}
boolean before() {
header( "Access-Control-Allow-Origin", "http://localhost:4200" )
boolean options = ("OPTIONS" == request.method)
if (options) {
header( "Access-Control-Allow-Origin", "http://localhost:4200" )
header( "Access-Control-Allow-Credentials", "true" )
header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
header( "Access-Control-Max-Age", "3600" )
response.status = 200
}
true
}
boolean after() { true }
}
现在 POST 和 PUT 请求正在运行。