与Rails 5做出反应,使用axios获得CSRF错误

Don*_*lio 6 ajax ruby-on-rails csrf reactjs axios

我正在尝试使用react_on_railsreact和rails构建我的第一个示例.我正在尝试将一些数据保存到rails后端,使用axios for ajax.

这是我的代码:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

和组件:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我点击提交时,我的后端报告

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):
Run Code Online (Sandbox Code Playgroud)

首先,我不明白为什么参数似乎被传递了两次,但这甚至都没有产生警告,所以现在不关心.

问题是我没有看到在我的反应代码中获取CSRF令牌以在post请求中使用的方法

我应该禁用CSRF吗?或者,还有更好的方法?

Pav*_*van 2

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

Rails通过附加到每个非 GET请求(POST、PUT/PATCH 和 DELETE )来处理CSRF攻击。该错误意味着您没有发送请求参数,您应该在 中附加一个唯一的参数,类似的内容应该可以解决问题。authenticity_tokenauthencity_token authenticity_tokenparams"authuenticity_token" => "BsfdgtZ1hshxgthjj"