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?
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:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.