Ruby+Vue前后端分离尝试

后端: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:这只是为了测试用例的完整性采用的解决方案,权限认证应该有更严谨的解决方案,这里就不再具体讨论了。

posted @ 2016-11-22 18:04  tzdk  阅读(3142)  评论(0编辑  收藏  举报