0

响应为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”,一切正常。

我错过了什么?

4

2 回答 2

4

牛仔的 content_types_provided 方法只接受 GET 和 HEAD

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

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

于 2013-06-28T07:44:37.690 回答
0

你可以使用 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}.
于 2017-09-05T13:32:23.017 回答