在我的烧瓶博客应用程序中,我使用AJAX来吸引用户'注释并将数据序列化为JSON并发布到应用程序的API。浏览器一直说我没有JSON的正确内容类型标题,并且评论没有发布。这对我来说似乎很好。我无法理解我在这里错过的东西。无论我提交评论,我都会说:
" message":"请求必须有\" Content-Type:application / json \"报头"
这是comments.js文件
Comments = window.Comments || {};
(function(exports, $) { /* Template string for rendering success or error messages. */
var alertMarkup = (
'<div class="alert alert-{class} alert-dismissable">' +
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
'<strong>{title}</strong> {body}</div>');
/* Create an alert element. */
function makeAlert(alertClass, title, body) {
var alertCopy = (alertMarkup
.replace('{class}', alertClass)
.replace('{title}', title)
.replace('{body}', body));
return $(alertCopy);
}
/* Retrieve the values from the form fields and return as an object. */
function getFormData(form) {
return {
'name': form.find('input#name').val(),
'email': form.find('input#email').val(),
'url': form.find('input#url').val(),
'body': form.find('textarea#body').val(),
'entry_id': form.find('input[name=entry_id]').val()
}
}
function bindHandler() {
/* When the comment form is submitted, serialize the form data as JSON
and POST it to the API. */
$('form#comment-form').on('submit', function() {
var form = $(this);
var formData = getFormData(form);
var request = $.ajax({
url: form.attr('action'),
type: 'POST',
data: JSON.stringify(formData),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
request.success(function(data) {
alertDiv = makeAlert('success', 'Success', 'your comment was posted.');
form.before(alertDiv);
form[0].reset();
});
request.fail(function() {
alertDiv = makeAlert('danger', 'Error', 'your comment was not posted.');
form.before(alertDiv);
});
return false;
});
}
exports.bindHandler = bindHandler;
})(Comments, jQuery);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
在我博客的帖子详细信息模板中,我还包含了comment.js文件。
{% extends "base.html" %}
{% block scripts %}
{{ super() }}
<script type="text/javascript" src="{{ url_for('static', filename='js/comments.js') }}"></script>
<script type="text/javascript">
$(function() {
Comments.bindHandler();
});
</script>
{% endblock %}
我还在helpers.py中编写了一个辅助函数,它接受反序列化的后期数据,将其提供给注释表单,以便在将数据写入数据库之前执行验证。
def post_preprocessor(data, **kwargs):
form = CommentForm(data=data)
if form.validate():
return form.data
else:
raise ProcessingException(
description='Invalid form submission.', code=400)
然后在我的app.py中,我有这个让API工作:
from helpers import post_preprocessor
api.create_api(
models.Comment,
include_columns=['id', 'name', 'url', 'body', 'created_timestamp'],
include_methods=['avatar'],
methods=['GET', 'POST'],
preprocessors={'POST': [post_preprocessor],
})