[英]How to take post request by ReactJs in Ruby On Rails?
作為標題,我試圖通過使用reactjs發布請求將新的表單數據發布到Rails服務器,但是我在控制台中得到了這個:
Started POST "/comments.json" for ::1 at 2016-11-19 02:56:47 +0800
Processing by CommentsController#create as JSON
Parameters: {"author"=>"v", "text"=>"c"}
Completed 400 Bad Request in 1ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: comment):
app/controllers/comments_controller.rb:73:in `comment_params'
app/controllers/comments_controller.rb:28:in `create'
控制器:
class CommentsController < ApplicationController
skip_before_filter :verify_authenticity_token
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def index
@comments = Comment.all
end
def create
@comment = Comment.new(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
def comment_params
params.require(:comment).permit(:author, :text)
end
end
反應部分
class CommentForm extends React.Component{
constructor(props){
super(props);
this.state ={
author: '',
text: ''
};
this.handleValueChange = this.handleValueChange.bind(this);
this.handleCreate = this.handleCreate.bind(this);
}
handleValueChange(event){
valueName = event.target.name;
this.setState({[valueName]: event.target.value});
};
handleCreate(event){
event.preventDefault();
$.ajax({
method: 'POST',
data: {
author: this.state.author,
text: this.state.text
},
url: '/comments.json'
});
console.log(this.state.author);
console.log(this.state.text);
};
render(){
console.log(this.state)
return(
<form onSubmit = {this.handleCreate.bind(this)} >
<label>Author</label>
<input type="text" placeholder="Author" value= {this.state.author} onChange={this.handleValueChange} name="author" />
<label>Text</label>
<input type="text" placeholder="Text" value= {this.state.text} onChange={this.handleValueChange} name="text" />
<input type="submit" value="Create" />
</form>
);
}
}
我不知道為什么帖子會收到400個請求,而參數卻丟失了。 我該如何解決?
您忘記添加標題。 Rails控制器會在根目錄中等待帶有注釋鍵的json模式。 還要調整網址。
params.require(:comment).permit(:author, :text)
=======
$.ajax({
method: 'POST',
data: { comment:{
author: this.state.author,
text: this.state.text
}
},
headers: {
'Content-Type': 'application/json'
},
url: '/comments'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.