$http POST 服务器错误

$http POST server error

我在尝试 POST 数据时遇到问题。我的服务器一直拒绝我的数据(500 服务器错误)。

这是我格式化的方式吗?我注意到我的控制台在 Response Headers 中显示 "Content-Type:text/html"。应该说 JSON 吗?

在 python 中,这工作正常:

requests.post('http://test.net/item/291/', {'uid':21, 'click':1, 'like':1, 'image':0, 'scroll':1, 'clickbuy':0})

我设置了一个中间件文件,其中包括:

class CorsMiddleware(object):

    def process_response(self, request, response):
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
        return response

我的 AngularJS 应用程序是这样设置的:

.factory('cardsApi', ['$http', function ($http) {
        var like = JSON.stringify({uid:21, click:1, like:1, image:0, scroll:1, clickbuy:0}));

        var postLikes = function (product_id) {
            return $http.post('http://test.com/api/item/' + product_id, like);
        }

        return {
            postLikes: postRecordLikes
        };
    }])

.config(function ($httpProvider) {
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
})

错误(在浏览器中):

答案在traceback you pasted底部的异常值中。

Exception Value: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to stashdapp-t51va1o0.cloudapp.net/api/item/37/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

对于 POST 请求,请确保 URL 与您的 urls.py 中定义的模式相匹配(或者您正在使用的任何第 3 方 Django 应用程序可能定义 URL 模式给你)。在这种情况下,您的 URL 模式包含一个尾部斜杠,因此您必须为 POST 请求包含一个带有 URL 的斜杠。

默认情况下,Django 自动重定向 URLs without trailing slashes to URLs with trailing slashes ,但是对于 POST 请求,您将丢失提交的数据,并且会引发此异常。

p.s。除非您已经尝试过并且出于某种原因它对您不起作用,否则我绝对建议您使用 django-cors-headers 应用程序,而不是使用您自己的中间件来处理 CORS。