0
votes

I am having a problem with cowboy REST request with method POST. It works fine if the POST done by submitting the Form content, but it will response when I use AJAX to send POST content to the server.

The error response is : 415 Unsupported Media Type

Here is my code for content_types_provided and content_types_accepted

content_types_accepted(Req, State) ->
    Handler = [
        {<<"text/html">>, handle_post_html},
        {{<<"application">>,<<"json">>, []}, handle_post_html},
        {{<<"text">>, <<"plain">>, []}, handle_post_html}],
    {Handler, Req, State}.

content_types_provided(Req, State)->
    Handler = [
        {<<"text/html">>, parse_html},
        {<<"application/json">>, parse_json},
        {<<"text/plain">>, parse_plain_text}],
    {Handler, Req, State}.

Any body has any idea on this case?

2
You can print Req and find which content type it contains. I think you should use something like {<<"application">>, <<"x-www-form-urlencoded">>, []} - P_A
Yes, I already add it, but when the post made by AJAX (XMLHTTPRequest) then it response 415. But works fine, if the post make by form submit button. - Yarin Nim

2 Answers

0
votes

Why separate it ?

Try it:

content_types_accepted(Req, State) ->
    Handler = [
        {<<"text/html">>, handle_post_html},
        {<<"application/json">>, handle_post_html},
        {<<"text/plain">>, handle_post_html}],
    {Handler, Req, State}.

content_types_provided(Req, State)->
    Handler = [
        {<<"text/html">>, parse_html},
        {<<"application/json">>, parse_json},
        {<<"text/plain">>, parse_plain_text}],
    {Handler, Req, State}.
0
votes

To make the cowboy understands the content type sent through XMLHTTPRequest (AJAX) with method POST, headers information need to be added in JavaScript as the followng:

<script language="javascript">
var content_types = {html:'text/html',json:'application/json',text:'text/plain',xml:'application/xml'};
    $(document).ready(function(){
        $('#btnPost').on('click', function(e){
            e.preventDefault();
            var href = 'http://localhost:8080/account-insert-12.html',
            var method = 'post',
            var resType = 'json'
            var postedData = $('#form').serialize();
            console.log(postedData);
            $.ajax({
                headers: {
                    'Accept': content_types[resType],
                    'Content-Type': content_types[resType] 
                },
                url:href, 
                type: method, 
                dataType: resType,
                data: postedData
            }).done(function(res){

            });
        });
    });
</script>