响应为 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”,一切都还可以。
我错过了什么?
答案 0 :(得分:3)
content_types_provided牛仔方法只接受GET和HEAD
浏览以下链接并相应更改代码
答案 1 :(得分: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}.