后端:Ruby On Rails提供API
前端:HTML+Vue+ajax
首先,初始化Ruby On Rails項目,並新建EmployeeModel和對應Controller,添加對應的CRUD方法,
class EmployeesController < ApplicationController def index #@employees = Employee.all json_str = Employee.all.to_json render :json=>json_str, status=>'200' end def new end def show @employee = Employee.find(params[:id]) end def create @employee = Employee.new(employee_params) @employee.save json_str = @employee.to_json render :json=>json_str, status=>'200' end def update @employee = Employee.find(params[:id]) if @employee.update(employee_params) json_str = @employee.to_json render :json=>json_str, status=>'200' else render 'edit' end end def destroy @employee = Employee.find(params[:id]) @employee.destroy json_str = @employee.to_json render :json=>json_str, status=>'200' end private def employee_params params.permit(:name, :gender,:age,:telephone) end end
前后端都是通過JSON進行通信的,所以對應的方法如果有返回值,需要轉成JSON格式,否則會報錯。
然后,前端HTML界面根據需要通過ajax調用對應的API接口,
$.ajax({ url: url, type: 'GET/Post', dataType: 'json', data: data, success: callback, error: function(xhr, errorType, error) { alert('error: ' + error) } })
前端效果圖,頁面布局來源:
需要注意的地方,主要在服務端,因為涉及到跨域以及CSRF驗證,所以需要在服務端進行相應的配置
1、跨域,打開Gemfile添加rack-cors gem,並install,代碼如下:
gem 'rack-cors', :require => 'rack/cors'
打開config/application.rb文件,添加以下代碼,為了測試方便,把put和delete操作也添加進去:
config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post,:put,:delete, :options] end end
2、去掉CSRF驗證,為了測試正常進行,所以暫時去掉,正常情況下不建議去掉CSRF驗證;在application_controller.rb文件中添加
protect_from_forgery with: :null_session
3、解決掉跨域和CSRF驗證以后,調用GET、POST方法是都沒問題,但是在調用PUT或者DELETE方法時,會提示找不到對應的路由設置,解決方法:在routes.rb文件中添加
match '*path' => 'application#cors_preflight_check', :via => :options
此時的頁面沒有權限認證,是不安全的,所有能訪問頁面的人都可以進行增刪改查操作,可以通過以下方法實現權限認證,
1、服務端提供用戶認證方法,在用戶登錄時,對用戶提供的用戶名和密碼信息進行驗證,如果用戶名和密碼匹配則驗證通過允許登錄,否則驗證失敗,
def create user = User.find_by(name: params[:username]) if user && user.authenticate(params[:password]) log_in user json_str = user.to_json render :json=>json_str, status=>'200' else #...todo end end
2、前端根據服務端的返回信息,如果驗證通過則把用戶信息記錄在sessionStorage中,並進行后續操作,如果驗證失敗,則提示用戶重新輸入用戶名和密碼,
3、用戶登錄以后,在界面中進行需要權限認證的操作時,需要由前端發起ajax請求,確認該用戶是否有相應的權限,首先在sessionStorage中取出用戶唯一性標示信息,如果sessionStorage中找不到對應的信息,則直接返回當前用戶無權限,提示用戶登錄,如果在sessionStorage中找到標示信息,則調用服務端API,sessionStorage標示信息作為入參傳入,服務端處理過程
# 返回當前登錄的用戶(如果有的話) def current_user @current_user ||= User.find_by(name: params[:userName]) end # 如果用戶已登錄,返回 true,否則返回 false def logged_in? !current_user.nil? end
4、根據入參可以找到對應的用戶信息,則認為該用戶有權限進行相應操作,如果找不到對應的用戶信息,則認為該用戶沒有權限進行相關操作。
在登錄的狀態下,可以進行刪除修改操作,在用戶注銷退出以后,如果在執行刪除操作時,會提示用戶登錄:
PS:這只是為了測試用例的完整性采用的解決方案,權限認證應該有更嚴謹的解決方案,這里就不再具體討論了。