【问题标题】:415 Unsupported Media Type Cowboy REST Ajax415 不支持的媒体类型 Cowboy REST Ajax
【发布时间】:2015-10-25 05:22:17
【问题描述】:

我在使用 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}.

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

【问题讨论】:

  • 您可以打印Req 并找到它包含的内容类型。我认为你应该使用类似{&lt;&lt;"application"&gt;&gt;, &lt;&lt;"x-www-form-urlencoded"&gt;&gt;, []}
  • 是的,我已经添加了,但是当通过 AJAX (XMLHTTPRequest) 发布帖子时,它会响应 415。但是如果帖子是通过表单提交按钮制作的,则可以正常工作。

标签: jquery ajax rest erlang cowboy


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    为什么要分开?

    试试看:

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

    【讨论】:

    • 是的,我已经尝试过了,但还是一样。使用单独是因为我需要使用 POST 和 PUT 方法,因为 content_types_provided 只处理标头(GET 方法),而 content_types_accepted 处理 Boby 内容(POST、PUT)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2019-05-01
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多