5
$http({method: 'POST', url: 'http://localhost:5001/products', data: {token: $scope.product.token}}).success(
    function () {
        alert('success');
    }
);

在金字塔一侧,request.POST 显示 NOVars: Not a form request。不是 HTML 表单提交(Content-Type: application/json)

我正在使用檐口来提供我的 api(/products),我认为这是金字塔的问题。

有没有人有办法解决吗?

4

6 回答 6

4

Angular 发送帖子正文(数据),application/json而表单通常发送为application/x-www-form-urlencoded. Pyramid 解析主体并让您在request.POST将其编码为正常形式时访问它。

不可能将每个以 Angular 方式 (json) 编码的数据表示为金字塔 API 提供的键/值对。

[
  1,
  2,
  3,
  4
]

金字塔侧的解决方案

它可以按视图或全局解决

每次观看

这是金字塔方式,也是最灵活的处理方式。

@view_config(renderer='json')
def myview(request):
    data = request.json_body
    # deal with data.
    return {
        "success" : True
    }

全球范围内

Pyramid 很可能被设置为假定一个编码为application/json对象的主体,其属性放在 request.POST 中。

Angular 方面的解决方案

与金字塔侧一样,它可以根据请求和全局解决。

根据请求

您需要以通常发送表单的方式发送数据:

$http({
  method: 'POST',
  url: url,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  transformRequest: function(obj) {
    var str = [];
    for(var p in obj) {
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    }
    return str.join("&");
  },
  data: xsrf
}).success(function () {});

全球范围内

要默认以表单形式发送帖子,请配置 $httpProvider 以执行此操作。

angular.module('httpPostAsForm', [])
.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (obj) {
     var str = [];
    for(var p in obj) {
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    }
    return str.join("&");
  });
}]);

然后在你的应用中包含这个模块:

angular.module("app", ["httpPostAsForm"]);
于 2014-12-10T16:56:19.383 回答
2

AngularJS $http.post 与 jquery 不同。您传递的数据不是以表单形式发布,而是以 json 形式发布在请求正文中。所以你的金字塔视图不能像往常一样解码它。您必须:

  • 直接访问请求正文并在您的金字塔视图中对其进行解码;
  • 或修改您的 angularjs 代码以将您的数据作为表单内容发布:请参阅stackoverflow 中的另一个问题
于 2014-04-15T09:00:52.203 回答
1

req.json_body如果您发布一些 json 解码的内容,请使用。req.GET, req.POST,req.params仅处理来自提交的内容。顺便说一句,$http -> ngResource -> restangular ...

于 2013-08-13T09:51:46.270 回答
1

答案是 angular $post 先做 OPTIONS 请求,然后做 POST 请求,从 request.json_body 获取数据

于 2013-07-22T07:07:44.477 回答
0

尝试在 $http 中设置 contenttype,如下所示。

 $http(
           {
               url: url,
               contentType: "application/json",
               data: data,
               method: method
           })
           .success(function (response) {
               successcb(response);
           }).error(function (data, status, headers, config) { errorcb(data); });
  };
于 2013-07-22T05:49:55.770 回答
0

您可以通过这种方式简单地获取 POST 数据:

query = json.loads(request.body)
于 2013-07-27T20:40:47.057 回答