erlang - Enabling CORS for Cowboy REST API -
how can enable cors cowboy rest handler? tried add options/2 method, this:
options(req, state) -> {[ {<<"access-control-allow-origin">>, <<"*">>}, {<<"access-control-allow-methods">>, <<"get, options">>} ], req, state}. but causes errors like:
error in process <0.263.0> exit value: {{case_clause,{[{<<27 bytes>>,<<1 byte>>},{<<28 bytes>>,<<12 bytes>>}],{http_req,#port<0.2636>,ranch_tcp,keepalive,<0.263.0>,<<7 bytes>>,{1,1},{{127,0,0,1},56522},<<9 bytes>>,undefined,9090,<<8 bytes>>,undefined,<<0 bytes>>,undefined,<<0 bytes>>,[],[{<<4 bytes>>,<<14 bytes>>},{<<10 bytes>>,<<74 bytes>>},{<<6 bytes>>,<<63 bytes>>},{<<15 bytes>>,<<14 bytes>>},{<<15 bytes>>,<<13 bytes>>},{<<6 bytes>>,<<4 bytes>>},{<<29 bytes>>,<<3 bytes>>},{<<30 bytes>>,<<16 bytes>>},{<<10 bytes>>,<<10 bytes>>}],[{<<10 bytes>>,[<<10 bytes>>]}],undefined,[],waiting,undefined,<<0 bytes>>,false,waiting,[],<<0 bytes>>,undefined},undefined... where mistake?
cowboy documentation says need set header using set_resp_headers, not return list of headers:
%% if need add additional headers response @ point, %% should directly in options/2 call using set_resp_headers. so code should like:
options(req, state) -> req1 = cowboy_req:set_resp_header(<<"access-control-allow-methods">>, <<"get, options">>, req), req2 = cowboy_req:set_resp_header(<<"access-control-allow-origin">>, <<"*">>, req1), {ok, req2, state}. you can test with
curl -h "origin: http://example.com" \ -h "access-control-request-method: get" \ -h "access-control-request-headers: x-requested-with" \ -x options --verbose \ http://localhost:8080 * connect() localhost port 8080 (#0) * trying 127.0.0.1... connected * connected localhost (127.0.0.1) port 8080 (#0) > options / http/1.1 > user-agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 openssl/0.9.8r zlib/1.2.5 > host: localhost:8080 > accept: */* > origin: http://example.com > access-control-request-method: > access-control-request-headers: x-requested-with > < http/1.1 200 ok < connection: keep-alive < server: cowboy < date: mon, 25 mar 2013 15:59:11 gmt < content-length: 0 < access-control-allow-methods: get, options < access-control-allow-origin: * < * connection #0 host localhost left intact * closing connection #0
Comments
Post a Comment