如何在AngularJS中将JSON数据发布到REST Web服务

沙爹拉维帕蒂

如何通过AngularJS将JSON数据发布到Web服务,这是代码片段

.controller('MessagePostCtrl', function($scope, $http) {
    $scope.postMessage = function() {
        var msg = document.getElementById('message').value;
        var msgdata = {
                message : msg
            };
        var res = $http.post('http://<domain-name>/messenger/api/posts/savePost',msgdata);
        res.success(function(data, status, headers, config) {
            console.log(data);
        });
    }
})

选项http:/// messenger / api / posts / savePost
ionic.bundle.js:16185(匿名函数)ionic.bundle.js:16185 sendReq ionic.bundle.js:15979 serverRequest ionic.bundle.js:15712包装的回调ionic。 bundle.js:19197包装的回调ionic.bundle.js:19197(匿名函数)ionic.bundle.js:19283 Scope。$ eval ionic.bundle.js:20326 Scope。$ digest ionic.bundle.js:20138 Scope。$ apply ionic.bundle.js:20430(匿名函数)ionic.bundle.js:43025(匿名函数)ionic.bundle.js:10478 for每个ionic.bundle.js:7950 eventHandler ionic.bundle.js:10477 triggerMouseEvent ionic.bundle。 js:2648 tapClick ionic.bundle.js:2637 tapMouseUp ionic.bundle.js:2707

XMLHttpRequest无法加载http:/// messenger / api / posts / savePost。无效的HTTP状态代码404

但是,当我从$ http.post方法中删除msgdata时,一切正常。谁能告诉我问题出在哪里,否则可以指导我如何将JSON数据发送到Web服务

谢谢您的帮助

**Edited:
The Issue was with the CORS, Im using codeigniter REST Controller for web-services.
Modified the headers. If anyone has the same issue add the below header in the construct

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
Thanks to Linial for the break-through, telling me where the issue is.**
线性的

好的,

您混淆了几件事:

首先,据我所知,您的请求已从POST更改为OPTIONS。

为什么?

您正在执行跨站点HTTP请求(CORS),这意味着您的WebApp和后端API不在同一域中。

实时发生的是该请求已被预检。

审核请求:Mozilla MDN提出:

它使用GET,HEAD或POST以外的方法。同样,如果POST用于发送请求类型为application / x-www-form-urlencoded,multipart / form-data或text / plain以外的Content-Type的请求数据,例如POST请求将XML有效负载发送给服务器使用application / xml或text / xml,则对请求进行预检。

这意味着,除GET,HEAD或POST之外的任何请求都将更改为OPTIONS AND:如果用于发送Content-Type以外的数据,则也为POST application/x-www-form-urlencoded, multipart/form-data, or text/plain

我现在明白了,但是该怎么办?我必须提出POST请求!

您没有太多选择,因为CORS是在服务器上定义的。

但是在客户端上,您可以这样做(示例):按如下所示更改angular的编码类型: $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

要么

设置服务器以批准CORS,如下所示:

Access-Control-Allow-Headers: Content-Type \\ This will allow you to set content type header in the client.

Access-Control-Allow-Methods: GET, POST, OPTIONS \\ This will allow you to send GET POST and OPTIONS, which is necessary because of preflighted requests.

Access-Control-Allow-Origin: * \\ This will allow anyone to perform CORS requests.

祝好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章