【问题标题】:AngularJS $http.post how to set the json data into request bodyAngularJS $http.post 如何将 json 数据设置为请求正文
【发布时间】:2017-04-27 17:25:16
【问题描述】:

我正在尝试将带有 json 数据的发布请求发送到服务器。但似乎 angularJS $http.post 方法没有将数据设置为正文。如何让它将数据设置为正文?

远程服务器使用 asp.net webapi 实现,将从正文中读取数据。所以我需要将 json 数据设置为请求正文。

请问我该如何实现?谢谢。

如果请求发送到同一个站点,那么它可以工作。但是如果我将请求发送到 CROS 服务器,它就不起作用。

在远程后端服务器中,我已经更新了 webconfig 以使其支持 CROS 调用,但仍然无法正常工作。

 $http.post(resourceUri, requestData)
    .success(function (response) {
    })
    .error(function (data, status, header, config) {
    });

【问题讨论】:

  • 谢谢大家。我终于找到了根本原因。这是由 CORS 调用引起的,需要在远程服务器上配置以支持后 CORS 调用。

标签: angularjs


【解决方案1】:

您可以像这样构建请求:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': "application/json"
 },
 data: { test: 'test' }
}

$http(req).success(function(){...}).error(function(){...});

【讨论】:

  • 为什么 Content-Type: undefined ?为什么不application/x-www-form-urlencoded
  • undefined?
【解决方案2】:

你可以这样做 1.制作控制器 2.在调用中添加数据

post调用的语法如下

$http.post(url, data, [config])

app.controller('controller', function ($scope, $http, $routeParams) {
        $http.post('url',data.call1($routeParams.id))
            .success(function (response) {
                 $scope.response = response;
            })
            .error(function (data, status, headers, config) {
            });
    });


var data = {
    call1:
        function (value) {
            return {'key': value, 'key': 'some text'};
         }
}

【讨论】:

  • 谢谢。我试过了,但它不起作用。我的代码是 $http.post(requestUri, dataObj) 在 fiddler 中跟踪请求详细信息时,我发现请求正文为空。后端服务器与我的应用程序不是同一个站点,这是 CROS 调用,但我的服务器已经配置为支持 CROS 调用。不知道如何使它工作。
  • 谢谢。 $http.post(url, data, [config]) 有效,但需要服务器端进行配置,让它支持 CORS 后调用。
猜你喜欢
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 2017-04-30
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
相关资源
最近更新 更多