【问题标题】:Restangular POST request not working as expectedRestangular POST 请求未按预期工作
【发布时间】:2015-04-11 16:25:21
【问题描述】:

我正在尝试向 REST api 发出 POST 请求。当我尝试使用带有以下代码的restangular时

 var cust={'name':'test'};
return Restangular.all('enquiry').post(cust).then(function(response) {
            console.log("Object saved OK");
        }, function(response) {
          console.log("There was an error saving");
          console.log(response);
        });

控制台出现错误

 XMLHttpRequest cannot load http://localhost/api/enquiry. The request was redirected to 'http://localhost/?search=', which is disallowed for cross-origin requests that require preflight.

这意味着服务器没有将请求视为 POST,因此 url 重定向不会转到正确的 API 页面

但是当我尝试使用 Google chrome REST 控制台发出 POST 请求时,它会转到正确的 API 页面并获得预期的结果

POST http://localhost/api/enquiry 502 (Bad Gateway)request.js:1 b.RESTRequest.Class.sendmootools-core-1.4.0.js:1 b.extend.$ownerapp.js:1 document.getElement.addEvents.submitmootools-core-1.4.0.js:1 (anonymous function)mootools-core-1.4.0.js:1 (anonymous function)mootools-core-1.4.0.js:1 Array.implement.eachmootools-core-1.4.0.js:1 invoke.fireEventapp.js:1 document.getElement.addEvents.postmootools-core-1.4.0.js:1 (anonymous function)mootools-core-1.4.0.js:1 (anonymous function)mootools-core-1.4.0.js:1 Array.implement.eachmootools-core-1.4.0.js:1 invoke.fireEventapp.js:1 document.getElement.addEvents.click:relay(input[type="button"], input[type="submit"], input[type="reset"])mootools-core-1.4.0.js:1 lmootools-core-1.4.0.js:1 dmootools-core-1.4.0.js:1 o

事件虽然 REST 控制台中的结果是 502 错误,但这是意料之中的。 我注意到使用 REST 控制台的输出是 POST http://localhost/api/enquiry 502 (Bad Gateway) 并且使用 restangular 它的 XMLHttpRequest 无法加载 http://localhost/api/enquiry 为什么通过 Restangular 发送的请求不考虑作为服务器中的 POST 请求,而是在 REST 控制台中工作?

服务器端接受的标头是

header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

【问题讨论】:

  • 您收到 CORS 错误检查您的服务器配置...
  • header("Access-Control-Allow-Origin: *");存在于服务器中,所以这会产生问题吗?

标签: angularjs rest restangular


【解决方案1】:

我已将 restangular POST 请求代码更改为

return Restangular.all('enquiry').post(cust,'',{'Content-Type': 'application/x-www-form-urlencoded'}).then(function(response) {
        console.log("Object saved OK");
    }, function(response) {
      console.log("There was an error saving");
      console.log(response);
    });

Content-type header 已经解决了这个问题。

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2014-11-12
    • 2018-05-14
    相关资源
    最近更新 更多