问题描述
我正在尝试使用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:
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错误以进行发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!