【问题标题】:Erlang Cowboy Rest Handler for POST request用于 POST 请求的 Erlang Cowboy Rest Handler
【发布时间】:2013-06-24 08:57:59
【问题描述】:

响应为 415(不支持的媒体类型)

客户端代码:

$.ajax({
      url: "/book",
      //contentType: 'application/json',
      data: {action: "hello", method: "json"},
      dataType: "json",
      type: "POST",
      complete: function(a, b) {
        console.log(a);
        console.log(b);
      }
    });

服务器端代码:

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

handle_to_all(Req, State) ->
    Body = <<"{\"rest\": \"Hello World!\"}">>,
    {Body, Req, State}.

如果我从客户端将类型从“POST”更新为“GET”,一切正常。

我错过了什么?

【问题讨论】:

    标签: rest erlang httprequest cowboy


    【解决方案1】:

    cowboy 的 content_types_provided 方法只接受 GET 和 HEAD

    通过以下链接并相应地更改代码

    https://ninenines.eu/docs/en/cowboy/1.0/manual/cowboy_rest/

    【讨论】:

    • 非常感谢,很有帮助。
    【解决方案2】:

    你可以使用cowboy_rest,像这样实现content_types_accepted/2回调方法:

     content_types_accepted(Req, State) ->
       case cowboy_req:method(Req) of
         {<<"POST">>, _ } ->
           Accepted = {[{<<"application/json">>, put_json}], Req, State};
         {<<"PUT">>, _ } ->
           Accepted = {[{<<"application/json">>, post_json}], Req, State}
       end,
     Accepted.
    

    我认为通过这种方式,您可以为不同的 HTTP 动词/方法设置单独的处理程序。这也为您提供了更简洁的代码:)

    以及各种处理程序:

     %% handle http put requests
     put_file(Req, State) ->
    
       {true, Req, State}.
     %% handle http post requests
     post_json(Req, State) ->
    
       {true, Req, State}.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2013-10-22
      • 2017-06-25
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多