2017-10-11 110 views
0

我想實現的REST處理程序,並有下面的代碼:牛仔 - REST回調不叫

-module(example_handler). 
-behaviour(cowboy_handler). 

-export([init/2, 
     allowed_methods/2, 
     content_types_provided/2, 
     get_json/2]). 

init(Req, State) -> 
    {cowboy_rest, Req, State}. 

allowed_methods(Req, State) -> 
    io:format("allowed_methods~n"), 
    {[<<"GET">>, <<"POST">>], Req, State}. 

content_types_provided(Req, State) -> 
    io:format("content_types_provided~n"), 
    {[{{<<"application">>, <<"json">>, []}, get_json}], Req, State}. 

get_json(_Req, _State) -> 
    io:format("get_json~n") 

然後,當我嘗試使用捲曲發送請求,這樣的:

curl -H "Accept: application/json" -X POST http://localhost:8080/xxx/xx 

我得到下一個輸出:

allowed_methods 
content_types_provided 

get_json()不被調用!但是,當我使用GET方法一切看起來不錯:

curl -H "Accept: application/json" -X GET http://localhost:8080/xxx/xx 
---------------------------------------------------------------------- 
allowed_methods 
content_types_provided 
get_json 

我錯過了什麼?

+1

如果你開始做你自己的東西,當你卡住的東西,特別是問一下這將是很好。 –

+0

@ɐuıɥɔɐɯ我改變了我的問題,你能回答嗎? – Hemul

回答

1

TL; DR

content_types_provided是不一樣的content_types_accepted;既然你正在處理POST你需要更晚。


Cowboy2.0.0,這是我用的,content_types_provided回調返回媒體類型資源的優先順序提供的列表。所以,當你使用:

content_types_provided(Req, State) -> 
    {[ 
    {{<<"application">>, <<"json">>, []}, get_json} 
    ], Req, State}. 

你基本上是告訴牛郎,從現在開始,這處理器支持JSON響應。這就是爲什麼當你做GET時,你將成功獲得HTTP 200 (OK) ...但POST不起作用。

另一方面,content_types_accepted回調允許狀態什麼content-types接受。你確實允許,因爲你在allowed_methods回調添加<<"POST">>發送POST請求,但會導致HTTP 415 (Unsupported Media Type)反應,因爲你還沒有告訴你要接受application/jsoncowboy_rest

這是應該爲你工作:

-module(example_handler). 

-export([init/2]). 

-export([ 
    allowed_methods/2, 
    content_types_accepted/2, 
    content_types_provided/2 
]). 

-export([get_json/2, post_json/2]). 

%%%============================================== 
%%% Exports 
%%%============================================== 
init(Req, Opts) -> 
    {cowboy_rest, Req, Opts}. 

allowed_methods(Req, State) -> 
    lager:debug("allowed_methods"), 
    {[<<"GET">>, <<"POST">>], Req, State}. 

content_types_accepted(Req, State) -> 
    lager:debug("content_types_accepted"), 
    {[ 
    {{<<"application">>, <<"json">>, []}, post_json} 
    ], Req, State}. 

content_types_provided(Req, State) -> 
    lager:debug("content_types_provided"), 
    {[ 
    {{<<"application">>, <<"json">>, []}, get_json} 
    ], Req, State}. 

get_json(Req, State) -> 
    lager:debug("get_json"), 
    {<<"{ \"hello\": \"there\" }">>, Req, State}. 

post_json(Req, State) -> 
    lager:debug("post_json"), 
    {true, Req, State}. 

%%%============================================== 
%%% Internal 
%%%============================================== 
+0

非常感謝!對我來說,這是合乎邏輯的,可恥的......我是Erlang的新手,但對它充滿熱情。 – Hemul