web-services - Angular JS POST 请求不发送 JSON 数据

标签 web-services http angularjs flask

我正在尝试将一个对象作为 JSON 发送到我在 Flask 中的 Web 服务,该服务期望请求数据中包含 JSON。

我已经通过发送 JSON 数据手动测试了该服务,它工作正常。但是,当我尝试通过 Angular Controller 发出 http POST 请求时,Web 服务器向我发送一条消息,说它没有收到 JSON。

当我检查 Chrome 中的请求 header 时,即使内容类型设置为 application/json,数据似乎也不是以 JSON 格式发送,而是常规键/值对发送

Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:49
Content-Type:application/json;charset=UTF-8
DNT:1
Host:localhost:5000
Origin:http://localhost:5000
Referer:http://localhost:5000/
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
application=AirFare&d1=10-APR-2013&d2=14-APR-2013

如果您看到 Request Payload 下面的最后一行,您可以看到数据不是 JSON 格式。

这是我的 Angular Controller 中的 HTTP POST 调用:

$http({
            url: '/user_to_itsr',
            method: "POST",
            data: {application:app, from:d1, to:d2},
            headers: {'Content-Type': 'application/json'}
        }).success(function (data, status, headers, config) {
                $scope.users = data.users; // assign  $scope.persons here as promise is resolved here 
            }).error(function (data, status, headers, config) {
                $scope.status = status + ' ' + headers;
            });
};  

我将数据作为对象 {} 发送,但我尝试在通过 JSON.stringify 序列化后发送它,但是,我似乎没有将 JSON 发送到服务器。

如果有人能提供帮助,我将不胜感激。

最佳答案

如果你正在序列化你的数据对象,它就不是一个合适的 json 对象。拿走你所有的,然后将数据对象包装在 JSON.stringify() 中。

$http({
    url: '/user_to_itsr',
    method: "POST",
    data: JSON.stringify({application:app, from:d1, to:d2}),
    headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
    $scope.users = data.users; // assign  $scope.persons here as promise is resolved here 
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

关于web-services - Angular JS POST 请求不发送 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17547227/

相关文章:

web-services - tomcat 上出现 CXF 错误的 Restful Web 服务

java - 在 Localhost 中配置 Tomcat 以通过代理进行通信 - Fiddler

javascript - Node.js 错误 : "Cannot assign to read only property ' _connections'"

java - Android - 让应用程序发送心跳到服务器

jquery - 如何在按下按钮时激活 Bootstrap 背景

java - org.apache.cxf.ws.policy.PolicyException : None of the policy alternatives can be satisfied

WCF Web 服务和 SSL 和证书

java - 在 Spring MVC REST 中返回文件

angularjs - 按翻译值对 ng-options 进行排序

javascript - AngularFire 数据未显示在列表应用程序中