Play2-React를 개발하던 중에 아래와 같은 에러가 크롬에서 발생했다.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
https://www.playframework.com/documentation/2.6.x/CorsFilter를 참고로 설정을 수정했다.
play.filters.enabled += "play.filters.cors.CORSFilter"
play.filters.cors {
pathPrefixes = ["/", ...]
allowedOrigins = ["http://localhost", ...]
allowedHttpMethods = ["GET", "POST"]
allowedHttpHeaders = ["Accept"]
preflightMaxAge = 3 days
}
처음에는 404, 정책을 잘 지정하지 못하면 403이 나타난다.
allowedOrigins = ["http://localhost:9000", ...]
다음과 같이 모두 개방하면 테스트는 편해진다. 상용에서는 보안을 위해서 잘 수정하는 것이 좋다.
(테스트용)
play.filters.hosts {
allowed = ["."]
}
(상용)
play.filters.hosts {
allowed = ["localhost", ".kakao.com", "localhost:9000", "local.google.com:9000", "local.google.com:4200"]
}
클라이언트(js)에서도 다음과 같이 수정한다.
superagent
.get('http://localhost:9000/log')
.set('http.cors.enabled', true)
.set('http.cors.allow-origin', "\"*\"")
.query({...})
.retry(2)
.end((err, res) => {
}
이제 요청하면 정상적으로 동작하는 지 확인할 수 있다.