后端:Ruby On Rails提供APIhtml
前端:HTML+Vue+ajax前端
首先,初始化Ruby On Rails项目,并新建EmployeeModel和对应Controller,添加对应的CRUD方法,git
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格式,不然会报错。github
而后,前端HTML界面根据须要经过ajax调用对应的API接口,ajax
$.ajax({ url: url, type: 'GET/Post', dataType: 'json', data: data, success: callback, error: function(xhr, errorType, error) { alert('error: ' + error) } })
前端效果图,页面布局来源:json
须要注意的地方,主要在服务端,由于涉及到跨域以及CSRF验证,因此须要在服务端进行相应的配置后端
一、跨域,打开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
二、去掉CSRF验证,为了测试正常进行,因此暂时去掉,正常状况下不建议去掉CSRF验证;在application_controller.rb文件中添加 session
protect_from_forgery with: :null_session
三、解决掉跨域和CSRF验证之后,调用GET、POST方法是都没问题,可是在调用PUT或者DELETE方法时,会提示找不到对应的路由设置,解决方法:在routes.rb文件中添加
match '*path' => 'application#cors_preflight_check', :via => :options
此时的页面没有权限认证,是不安全的,全部能访问页面的人均可以进行增删改查操做,能够经过如下方法实现权限认证,
一、服务端提供用户认证方法,在用户登陆时,对用户提供的用户名和密码信息进行验证,若是用户名和密码匹配则验证经过容许登陆,不然验证失败,
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
二、前端根据服务端的返回信息,若是验证经过则把用户信息记录在sessionStorage中,并进行后续操做,若是验证失败,则提示用户从新输入用户名和密码,
三、用户登陆之后,在界面中进行须要权限认证的操做时,须要由前端发起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
四、根据入参能够找到对应的用户信息,则认为该用户有权限进行相应操做,若是找不到对应的用户信息,则认为该用户没有权限进行相关操做。
在登陆的状态下,能够进行删除修改操做,在用户注销退出之后,若是在执行删除操做时,会提示用户登陆:
PS:这只是为了测试用例的完整性采用的解决方案,权限认证应该有更严谨的解决方案,这里就再也不具体讨论了。