Restangular POST请求未按预期工作

时间:2015-02-11 10:29:06

标签: angularjs rest restangular

我正在尝试向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");

1 个答案:

答案 0 :(得分:0)

我已将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标头解决了这个问题。