2015-02-11 51 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頭已經解決了這個問題。