发送JSON到Rails REST API
问题描述:
我有一个Rails应用程序,包含文章和用户。 所以我希望用户可以从客户端应用程序用json对象注销并获取所有文章也用json对象。发送JSON到Rails REST API
但是,我有一些问题。控制台输出:
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
而这里的Controler:
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令牌?
答
您需要确保CSRF令牌随每个JSON HTTP请求一起提交。这就是我的做法:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});