2015-02-11 56 views
1

我正在尝试向REST API执行POST请求。当我尝试使用restangular用下面的代码Restangular POST请求不按预期方式工作

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页面

但是当我试图与谷歌浏览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(坏的网关)和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"); 
+0

您正在收到CORS错误检查您的服务器配置... – 2015-02-11 10:46:04

+0

header(“Access-Control-Allow-Origin:*”);存在于服务器中,所以这会造成问题。 – Aswanth 2015-02-11 11:05:07

回答

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