[英]react with Rails 5, getting CSRF error for post with axios
我正在嘗試使用react_on_rails
構建第一個帶有react和rails的示例。 我正在嘗試使用axios作為ajax將一些數據保存到rails后端。
這是我的代碼:
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嗎? 或者,還有更好的方法?
ActionController :: InvalidAuthenticityToken(ActionController :: InvalidAuthenticityToken):
Rails通過將authenticity_token
附加到每個非GET請求( POST,PUT / PATCH和DELETE )來處理CSRF攻擊。 你是不是在發送錯誤意味着authencity_token
的請求參數 ,你應該一個獨特的附加authenticity_token
到params
,像"authuenticity_token" => "BsfdgtZ1hshxgthjj"
這應該解決的問題。
react_on_rails
通過提供兩個幫助程序來解決此問題。 從react_on_rails
文檔中 :
Rails具有跨站點請求偽造(CSRF)的內置保護,請參見Rails文檔。 為了在JavaScript請求中很好地利用此功能,React on Rails提供了兩個幫助程序,可用於以下POST,PUT或DELETE請求:
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);
我發現react_on_rails
有一個輔助系統來處理CSRF令牌,
它基本上使用:
<%= csrf_meta_tags %>
將csrf_token作為元添加到頁面的標題中
然后您可以使用:
import ReactOnRails from "react-on-rails";
export function saveNameAction(name) {
console.log("creating action " + name);
return {
authenticity_token: ReactOnRails.authenticityToken(),
type: SAVE_NAME,
name
};
}
來獲取並使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.