rest - 为 Cowboy REST API 启用 CORS

标签 rest erlang cors cowboy

如何为牛仔休息处理程序启用 CORS?
我尝试添加 options/2 方法,如下所示:

options(Req, State) ->
    {[
       {<<"access-control-allow-origin">>, <<"*">>},
       {<<"access-control-allow-methods">>, <<"GET, OPTIONS">>}
     ], Req, State}.

但这会导致错误,例如:
Error in process <0.263.0> with 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...

我的错误在哪里?

最佳答案

Cowboy 文档说您需要使用 set_resp_headers 设置标题,而不是返回标题列表:

 %% If you need to add additional headers to the response at this point,
 %% you should do it directly in the options/2 call using set_resp_headers.

所以你的代码应该是这样的:
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}.

你可以测试
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
* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1... connected
* Connected to 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: GET
> 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 to host localhost left intact
* Closing connection #0

关于rest - 为 Cowboy REST API 启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15616027/

相关文章:

java - 使用 Tomcat 对 json POST 的错误请求

javascript - Angular 2+ 从 http 请求返回变量或映射

binary - Erlang io:将二进制格式格式化为十六进制

erlang - 如何告诉 rebar3 在依赖项中运行测试

erlang - 何时在 Elixir 中使用 Agent 而不是 GenServer

azure - 如何使用 postman 将图像上传到azure blob存储

python - 如何将Heruko与本地计算机的Docker API(Python SDK)结合使用?

javascript - 为什么 jQuery 在我的 Ajax 请求中包含 Origin header 以及如何从中删除它?

javascript - 谷歌跨源请求

angular - 使用 spring 和 docker 抛出运行时异常时的 cors 问题