2014-10-05 72 views
0

我有一個'Create Account'視圖,我正在開始工作。 Backbone 1.1.2(typescript)前端,Rails 4.2 beta 1 Web服務後端。骨幹model.save()導致OPTIONS而不是POST

帳戶型號

export class Account extends Backbone.Model { 
    public urlRoot: string; 
    public validation:any; 

    constructor(attributes?: any, options?: any){ 
     this.urlRoot = 'http://domain.fake/accounts'; 
     this.validation = { 
      email: { 
       required: true, 
       pattern: 'email' 
      }, 
      password: { 
       required: true, 
       minLength: 6 
      } 
     }; 
     super(attributes, options); 
    } 
} 

創建的帳戶查看:上model.save()

export class CreateAccountView extends Backbone.View { 
    public template: string; 
    public events: any; 
    public model: accountModelImport.Account; 

    constructor(options?: Backbone.ViewOptions){ 
     this.el = '#modal'; 
     this.template = createAccountViewTemplate; 
     this.model = new accountModelImport.Account(); 
     this.events = { 
      'click #create-account-submit' : 'create' 
     }; 
     super(options); 
    } 

    public render(): CreateAccountView { 
     this.$el.html(_.template(this.template)); 
     Backbone.Validation.bind(this); 
     this.$el.modal('show'); 
     return this; 
    } 

    public create(){ 
     var email:string = $('#create-account-email').val(), password:string = $('#create-account-password').val(), passconf:string = $('#create-account-password-confirmation').val(); 
     this.model.set({email: email, password: password, password_confirmation: passconf}); 
     this.model.save(null, {success: this.success, error: this.error}); 
    } 

    public success(){ 
     alert('Success'); 
    } 

    public error(){ 
     alert('error'); 
    } 
} 

Rails的輸出從上面:

ActionController::RoutingError (No route matches [OPTIONS] "/accounts"): 

我看到什麼傳遞的第一個參數.save()很多問題,我每次它們都試過了同樣的結果:null, false, {}

我曾試圖用同樣的問題尋找一個問題,但都沒有能找到一個。我想在嘗試覆蓋.sync()方法之前嘗試讓它在本地生效。

爲什麼.save()試圖使用OPTIONS而不是POST

回答

0

正如在他的回答中指出@meagar這個問題,這不是任何骨幹試圖做是錯誤的。這是一個CORS問題。我使用config.action_dispatch.default_headers.merge!手動設置了標題,但顯然這還不夠。

多一點陶醉谷歌搜索答案的這個小寶石,我(得到它,「寶石」)... Rails RoutingError (No route matches [OPTIONS]

這個問題的答案也使我https://github.com/cyu/rack-cors

安裝寶石,按照他們的指令配置後,POST請求經歷了預期。

希望這可以幫助別人在將來,並且一定要把@meagar歸功於幫助我走上正確的道路。

3

爲什麼.save()試圖使用OPTIONS而不是POST?

不是。這是工作中的CORS「預檢請求」。如果OPTIONS請求成功,則POST請求將隨之發生。

...預檢請求是作爲一個HTTP OPTIONS請求(因此 確定您的服務器能夠響應此方法)。它還包含 幾個附加標題:

訪問控制請求方法 - 實際請求的HTTP方法。 即使HTTP方法是前面定義的簡單HTTP方法(GET,POST,HEAD),也始終包含此請求標頭。

訪問控制請求頭 - 包含在請求中的非簡單 頭的逗號分隔列表。

在發出實際請求之前,預檢請求是一種詢問實際請求的權限的方法。服務器應檢查上述兩個標頭 ,以驗證HTTP方法和請求標頭是否有效並被接受。

http://www.html5rocks.com/en/tutorials/cors/