繁体   English   中英

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

[英]415 Unsupported Media Type Cowboy REST Ajax

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

有谁对此案有任何想法?

为什么要分开呢?

试试吧:

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方法通过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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM