【问题标题】:$http POST server error$http POST 服务器错误
【发布时间】:2016-03-29 10:53:04
【问题描述】:

我在尝试 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 = {};
})

错误(在浏览器中):

【问题讨论】:

  • 您的服务器在处理请求时遇到问题。尝试删除stringify 位,所以var like = { blah blah blah };
  • 您的意思是删除整个 JSON.stringify 吗?我这样做了,仍然收到 500 错误。我注意到在响应标题中它说内容类型是 Text/html
  • 好吧,如果没有更多信息,它看起来像是服务器代码的问题,而不是角度问题。尝试设置一个展示问题的小提琴。
  • 当然,我已经做到了:plnkr.co/edit/7ScnGyy2eAmGwcJ7XZ2Z?p=preview
  • @Ycon 500 错误意味着在处理请求时引发了 Python 异常。查看运行 Django 开发服务器的终端输出。发生错误时应该有回溯。您可以发布该追溯的粘贴箱吗?

标签: angularjs django http django-cors-headers


【解决方案1】:

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

默认情况下,Django 会自动将 斜杠的 URL 重定向到 斜杠的 URL,但是对于 POST 请求,您将丢失提交的数据并且会引发此异常.

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

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 2023-02-20
    • 2016-09-15
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2012-03-16
    • 2021-09-07
    相关资源
    最近更新 更多