$ http POST服务器错误

时间:2015-12-23 03:46:10

标签: angularjs django http cors django-cors-headers

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

这是我格式化的方式吗?我在响应标题的控制台中注意到它显示“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 = {};
})

错误(在浏览器中):

enter image description here

1 个答案:

答案 0 :(得分:0)

答案在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中定义的模式(或者您正在使用的任何第三方Django应用程序,可能正在为您定义URL模式)。在这种情况下,您的URL模式包含一个尾部斜杠,因此您必须包含一个带有POST请求的URL。

默认情况下,Django自动将没有尾部斜杠的重定向到带有尾部斜杠的URL ,但对于POST请求,您将丢失提交的数据,此异常将被抚养长大。

P.S。除非你已经尝试过它,并且有一些原因它不适合你,我绝对建议使用django-cors-headers应用程序,而不是滚动你自己的中间件处理CORS。