[英]415 Unsupported Media Type Cowboy REST Ajax
I am having a problem with cowboy REST request with method POST. 我在使用POST方法的牛仔REST请求中遇到问题。 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.
如果POST通过提交表单内容来完成,则效果很好,但是当我使用AJAX将POST内容发送到服务器时,它将响应。
The error response is : 415 Unsupported Media Type 错误响应是:415不支持的媒体类型
Here is my code for content_types_provided and content_types_accepted 这是我的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}.
Any body has any idea on this case? 有谁对此案有任何想法?
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}.
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: 为了使牛仔了解使用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.