content_types_provided method of cowboy accepts only GET and HEAD
Go through the following link and change the code accordingly
Question
The response is 415 (Unsupported Media Type) .
Client Side Code:
$.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);
}
});
Server Side Code:
content_types_provided(Req, State) ->
{[
{<<"application/json">>, handle_to_all}
], Req, State}.
handle_to_all(Req, State) ->
Body = <<"{\"rest\": \"Hello World!\"}">>,
{Body, Req, State}.
If I update the type from "POST" to "GET" from client side, everything is okay.
Anything I missed?
La solution
content_types_provided method of cowboy accepts only GET and HEAD
Go through the following link and change the code accordingly
Autres conseils
You can use cowboy_rest, implement the content_types_accepted/2 callback method like so:
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.
I think this way you can have separate handlers for different HTTP Verbs/Methods. This gives you cleaner code too :)
And the various handlers:
%% handle http put requests
put_file(Req, State) ->
{true, Req, State}.
%% handle http post requests
post_json(Req, State) ->
{true, Req, State}.