415不支持的媒体类型Cowboy REST Ajax

时间:2015-08-03 07:23:37

标签: jquery ajax rest erlang cowboy

我遇到了使用方法POST的牛仔REST请求的问题。如果通过提交表单内容完成POST,它可以正常工作,但是当我使用AJAX将POST内容发送到服务器时它会响应。

错误回复是: 415不支持的媒体类型

这是我的content_types_provided和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}.

任何机构都对此案有任何想法?

2 个答案:

答案 0 :(得分:0)

为什么将其分开?

试一试:

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}.

答案 1 :(得分:0)

为了让牛仔了解通过方法POST通过XMLHTTPRequest(AJAX)发送的内容类型,需要在JavaScript中添加标题信息,如下所示:

<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>