Отправить JSON в Rails REST API - PullRequest
       1

Отправить JSON в Rails REST API

0 голосов
/ 30 марта 2012

У меня есть приложение Rails со статьями и пользователями.Поэтому я хочу, чтобы пользователь мог выйти из клиентского приложения с помощью объекта json и получить всю статью также с помощью объекта json.

Но у меня есть некоторые проблемы.Консольный вывод:

Started POST "/articles" for 127.0.0.1 at 2012-03-30 17:29:25 +0200
Processing by ArticlesController#create as JSON
  Parameters: {"id"=>1, "article"=>{"id"=>1}}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 1ms

А вот контроллер:

class ArticlesController < ApplicationController
  before_filter :authenticate_user!, :except => [:show, :index]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @articles }
    end
  end

  # GET /articles/1
  # GET /articles/1.json
  def show
    @article = Article.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @article }
    end
  end

  # GET /articles/new
  # GET /articles/new.json
  def new
    @article = Article.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @article }
    end
  end

  # GET /articles/1/edit
  def edit
    @article = Article.find(params[:id])
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(params[:article])

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article was successfully created.' }
        format.json { render json: @article, status: :created, location: @article }
      else
        format.html { render action: "new" }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /articles/1
  # PUT /articles/1.json
  def update
    @article = Article.find(params[:id])

    respond_to do |format|
      if @article.update_attributes(params[:article])
        format.html { redirect_to @article, notice: 'Article was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.json
  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    respond_to do |format|
      format.html { redirect_to articles_url }
      format.json { head :no_content }
    end
  end
end

И модель:

class Article < ActiveRecord::Base

end

JSON, который я посылаю, выглядит так:

{
  "id" : 1
}

Маршруты

                   articles GET        /articles(.:format)                       articles#index
                        POST       /articles(.:format)                       articles#create
            new_article GET        /articles/new(.:format)                   articles#new
           edit_article GET        /articles/:id/edit(.:format)              articles#edit
                article GET        /articles/:id(.:format)                   articles#show
                        PUT        /articles/:id(.:format)                   articles#update
                        DELETE     /articles/:id(.:format)                   articles#destroy
                   root            /                                         articles#index

Теперь мой вопрос: мой объект JSON неверен или я что-то упускаю, например токен CSRF?

1 Ответ

1 голос
/ 21 мая 2012

Необходимо убедиться, что токен CSRF передается с каждым HTTP-запросом JSON.Вот как я это делаю:

$.ajaxSetup({
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
}); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...