Champer Wu Champer Wu - 18 days ago 7
React JSX Question

How to take post request by ReactJs in Ruby On Rails?

As title, I tried to post my new form data to the rails server by using reactjs post request, but I got this in console:

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'


Controller:

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


React part

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>
);
}


}

I don't know why post will get 400 request, and the param is missing.
How can I fix it?

Answer

You forget to add headers. And rails controller waits your json schema with comment key in root. Also url adjusted.

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'
    });