【问题标题】:How to take post request by ReactJs in Ruby On Rails?如何在 Ruby On Rails 中接受 ReactJs 的发布请求?
【发布时间】:2023-04-03 19:05:01
【问题描述】:

作为标题,我尝试使用 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>
    );
}

}

我不知道为什么 post 会收到 400 个请求,并且缺少参数。 我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby reactjs


    【解决方案1】:

    您忘记添加标题。 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'
        });
    

    【讨论】:

    • 我有新问题,日志显示:Started POST "/comments.json" for ::1 at 2016-11-19 04:21:36 +0800 Error occurred while parsing request parameters. Contents: author=dd&amp;text=aa ActionDispatch::ParamsParser::ParseError (795: unexpected token at 'author=dd&amp;text=aa'):
    • 我删除了标题和数据使用你的代码。我成功发布数据,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多