17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PlayでCORS対策

Posted at

playframeworkで作成したREST APIを別オリジンから呼ぶ場合、CORS対策が必要になる。
参考:Cross-origin resource sharing(wikipedia)

すごく簡単に言うとレスポンスヘッダに「Access-Control-Allow-Origin: *」を付加すれば良いわけだけど、
各メソッドでいちいちやるのもあれだし、Global.javaでインターセプトする。

Global.java
import play.*;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.SimpleResult;
import java.lang.reflect.Method;

public class Global extends GlobalSettings{

    // CORS対応
    private class ActionWrapper extends Action.Simple {
        public ActionWrapper(Action<?> action) {
            this.delegate = action;
        }

        @Override
        public Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
            Promise<SimpleResult> result = this.delegate.call(ctx);
            Http.Response response = ctx.response();
            response.setHeader("Access-Control-Allow-Origin", "*");
            return result;
        }
    }

    @Override
    public Action<?> onRequest(Http.Request request, Method actionMethod) {
        return new ActionWrapper(super.onRequest(request, actionMethod));
    }
}

参考

ほぼ丸コピさせていただきました。
Thanks StackOverflow

17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?