2017-07-07 99 views
2

我正在嘗試使用react_on_rails來構建我的第一個反應和rails示例。我試圖將一些數據保存到rails後端,使用axios作爲ajax。與Rails 5反應,爲axios發佈CSRF錯誤

這裏是我的代碼:

import store from "../store/helloWorld"; 
import axios from "axios"; 

export const SAVE_NAME = "SAVE_NAME"; 

export function saveNameAction(name) { 
    return { 
    type: SAVE_NAME, 
    name 
    }; 
} 

export function saveName(name) { 
    axios 
    .post("/hello_world", saveNameAction(name)) 
    .then(function(response) { 
     console.log(response); 
    }) 
    .catch(function(error) { 
     console.log(error); 
    }); 
} 

和組件:

import PropTypes from "prop-types"; 
import React from "react"; 
import * as actions from "../actions/helloWorld"; 

export default class HelloWorld extends React.Component { 
    static propTypes = { 
    name: PropTypes.string.isRequired // this is passed from the Rails view 
    }; 

    /** 
    * @param props - Comes from your rails view. 
    */ 
    constructor(props) { 
    super(props); 
    this.state = { name: this.props.name }; 
    } 

    updateName(name) { 
    this.setState({ name: name }); 
    } 

    handleSubmit(event) { 
    event.preventDefault(); 
    actions.saveName(this.state.name); 
    } 

    render() { 
    return (
     <div> 
     <h3> 
      Hellopp, {this.state.name}! 
     </h3> 
     <hr /> 
     <form> 
      <label htmlFor="name">Say hello to:</label> 
      <input 
      id="name" 
      type="text" 
      value={this.state.name} 
      onChange={e => this.updateName(e.target.value)} 
      /> 

      <input 
      type="submit" 
      value="Submit" 
      onClick={event => this.handleSubmit(event)} 
      /> 
     </form> 
     </div> 
    ); 
    } 
} 

的問題是,當我點擊提交,我的後端報告

Started POST "/hello_world" for ::1 at 2017-07-07 15:30:44 +0200 
Processing by HelloWorldController#create as HTML 
    Parameters: {"type"=>"SAVE_NAME", "name"=>"Stranger", "hello_world"=>{"type"=>"SAVE_NAME", "name"=>"Stranger"}} 
Can't verify CSRF token authenticity. 
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms) 

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): 

首先,我不'不明白爲什麼參數似乎會被傳遞兩次,但這甚至不會產生警告,所以現在不要在意。

的問題是,我不明白的方式來獲得CSRF令牌在我的反應代碼在post請求

我應該禁用CSRF使用?或者,還有更好的方法?

回答

0

的ActionController :: InvalidAuthenticityToken (ActionController的:: InvalidAuthenticityToken):

導軌通過附加authenticity_token來處理CSRF攻擊每非GET請求POST,PUT/PATCH和DELETE) 。錯誤表示您沒有在請求參數中發送authencity_token,您應該附加唯一authenticity_tokenparams,類似"authuenticity_token" => "BsfdgtZ1hshxgthjj"這應該可以解決問題。

0

我發現react_on_rails有一個助手系統來處理CSRF令牌,

它主要用途:

<%= csrf_meta_tags %> 

在頁面csrf_token添加到標題爲元

和那麼您可以使用:

import ReactOnRails from "react-on-rails"; 

export function saveNameAction(name) { 
    console.log("creating action " + name); 
    return { 
    authenticity_token: ReactOnRails.authenticityToken(), 
    type: SAVE_NAME, 
    name 
    }; 
} 

將其取出d使用它。

+0

我唯一的疑問是'authenticity_token'硬連線,而在標題中,我看到'csrf-param'設置標記的名稱。 –