我正在嘗試使用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使用?或者,還有更好的方法?
我唯一的疑問是'authenticity_token'硬連線,而在標題中,我看到'csrf-param'設置標記的名稱。 –