我嘗試使用Rails API發佈json文件。 我有嘗試解決,但不能運行 這是我的問題:無法驗證CSRF令牌的真實性!使用POST的RAILS API
Sever的日誌:
Started POST "/students/" for 127.0.0.1 at 2016-09-17 17:45:33 +0700
ActiveRecord::SchemaMigration Load (0.0ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Devise::RegistrationsController#create as */*
Parameters: {"student"=>{"name"=>"Duong", "score"=>"10"}, "registration"=>{"student"=>{"name"=>"Duong", "score"=>"10"}}}
Can't verify CSRF token authenticity.
Unpermitted parameters: name, score
(0.0ms) begin transaction
(0.0ms) rollback transaction
Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/shared/_links.html.erb (10.0ms)
Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application (60.0ms)
Completed 500 Internal Server Error in 442ms (ActiveRecord: 0.0ms)
Student.rb
這是我的學生模型
class Student < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Application_controller
我已修復excetion => null_se裂變
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
Student_controller
class Api::StudentsController < ApplicationController
def index
students = Student.all
render json: students, status: 200
end
def show
response_with Student.find(params[:id])
end
def create
student = Student.new(student_params)
#if you save successfully than response with json data and status code 201
if student.save
render json: user, status: 201, location: student
else
render json: {error: user.errors}, status: 422
end
end
private
def student_params
params.require(:student).permit(:name, :score)
end
end
router.rb
Rails.application.routes.draw do
devise_for :students
namespace :api, path: '/',constraints: {subdomain: 'api'} do
resources :students, only: [:index, :show, :create]
end
end
但是,當我發個帖子api.1312100.com/students/
{"student": {"name": "Duong", "score": "10"}}
有錯誤:
500 internal server error
你有 <%= csrf_meta_tags%>在您的
? – luissimo哪裏在
? –我不能多說CSRF錯誤。但你必須解決'未經許可的參數:名稱,分數'錯誤。嘗試白名單這些參數,即名稱和分數 – Sajan