我正在尝试使用react_on_rails
react 和 rails 来构建我的第一个示例。我正在尝试将一些数据保存到 rails 后端,将 axios 用于 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>
);
}
}
问题是当我点击提交时,我的后端报告
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):
一方面,我不明白为什么参数似乎被传递了两次,但这甚至没有产生警告,所以现在不要在意。
问题是我没有看到在我的react代码中获取 CSRF 令牌以在post
请求中使用的方法
我应该禁用CSRF吗?或者,还有更好的方法?