与Rails 5反应,使用axios获取CSRF错误以进行发布 [英] react with Rails 5, getting CSRF error for post with axios

查看:88
本文介绍了与Rails 5反应,使用axios获取CSRF错误以进行发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用react_on_rails来构建我的第一个带有react和rails的示例.我正在尝试使用axios作为ajax将一些数据保存到rails后端.

I'm trying to use react_on_rails to build my first example with react and rails. I'm trying to save some data to the rails backend, using axios for the 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);
    });
}

和组件:

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>
    );
  }
}

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

The problem is that when I click the submit, my backend reports

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):

有一个原因,我不明白为什么参数似乎要被两次传递,但这甚至没有生成警告,所以现在就不在乎.

For one, I don't understand why the parameters seem to be passed twice, but that's not even generating a warning, so don't care for now.

问题是我找不到在我的React代码中用于获取post请求的CSRF令牌的方法

The problem is that I don't see a way to obtain the CSRF tokens in my react code to use in the post requests

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

should I just disable CSRF? or is there a better way?

推荐答案

react_on_rails通过提供两个帮助程序来解决此问题.从react_on_rails 文档:

react_on_rails deals with this issue by providing two helpers. From the react_on_rails documentation:

Rails具有跨站点请求伪造(CSRF)的内置保护,请参见Rails文档.为了在JavaScript请求中很好地利用此功能,React on Rails提供了两个帮助程序,可用于以下POST,PUT或DELETE请求:

Rails has built-in protection for Cross-Site Request Forgery (CSRF), see Rails Documentation. To nicely utilize this feature in JavaScript requests, React on Rails provides two helpers that can be used as following for POST, PUT or DELETE requests:

import ReactOnRails from 'react-on-rails';

// reads from DOM csrf token generated by Rails in <%= csrf_meta_tags %>
csrfToken = ReactOnRails.authenticityToken();

// compose Rails specific request header as following { X-CSRF-Token: csrfToken, X-Requested-With: XMLHttpRequest }
header = ReactOnRails.authenticityHeaders(otherHeader);

这篇关于与Rails 5反应,使用axios获取CSRF错误以进行发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆