如何实现react-fine-uploader结合redux-token-auth的后端认证上传?
解决react-fine-uploader结合redux-token-auth(devise_token_auth后端)的认证上传问题
咱们先明确核心:devise_token_auth要求的认证头是access-token、client、uid这三个,redux-token-auth会把它们存在localStorage或者Redux Store里。下面分两种规范的方法实现认证上传:
方法一:从Redux Store读取认证信息(推荐)
既然用了Redux,直接从store取认证数据比读localStorage更符合数据流规范。redux-token-auth会把用户认证状态存在store.auth节点下:
import { useSelector } from 'react-redux'; import FineUploaderTraditional from 'react-fine-uploader-traditional'; import 'react-fine-uploader-traditional/dist/fineuploader.css'; const ImageUploader = () => { // 从Redux Store提取认证核心字段 const { accessToken, client, uid } = useSelector(state => state.auth); // 组装认证头(未登录时为空对象,避免报错) const authHeaders = accessToken ? { 'access-token': accessToken, 'client': client, 'uid': uid } : {}; return ( <FineUploaderTraditional options={{ request: { endpoint: '/api/v1/uploads', // 替换成你的Rails后端上传接口 customHeaders: authHeaders // 把认证头注入请求 }, // 可选:配置文件验证规则 validation: { allowedExtensions: ['jpeg', 'jpg', 'png'], sizeLimit: 5 * 1024 * 1024 // 限制5MB以内 }, // 可选:处理上传错误(比如令牌过期) callbacks: { onError: (id, name, errorReason, xhr) => { if (xhr?.status === 401) { // 这里可以触发redux-token-auth的刷新令牌动作,比如dispatch(refreshAuthToken()) // 刷新成功后可重新触发该文件的上传 } } } }} /> ); }; export default ImageUploader;
方法二:直接从localStorage读取认证头
如果暂时不想依赖Redux Store,也可以直接读取redux-token-auth存在localStorage里的数据(默认存储键为reduxTokenAuth):
import FineUploaderTraditional from 'react-fine-uploader-traditional'; import 'react-fine-uploader-traditional/dist/fineuploader.css'; const ImageUploader = () => { // 从localStorage提取认证数据 const getAuthHeaders = () => { const authData = JSON.parse(localStorage.getItem('reduxTokenAuth')); if (!authData) return {}; return { 'access-token': authData.accessToken, 'client': authData.client, 'uid': authData.uid }; }; return ( <FineUploaderTraditional options={{ request: { endpoint: '/api/v1/uploads', customHeaders: getAuthHeaders() }, validation: { allowedExtensions: ['jpeg', 'jpg', 'png'] } }} /> ); }; export default ImageUploader;
Rails后端配套配置
1. CORS设置(必须)
确保Rails允许前端跨域请求携带认证头,修改config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'http://localhost:3000' # 生产环境替换成你的前端域名 resource '*', headers: :any, expose: ['access-token', 'client', 'uid'], # 把认证头暴露给前端 methods: [:get, :post, :put, :patch, :delete, :options, :head] end end
2. 上传控制器认证
让上传控制器继承DeviseTokenAuth::ApplicationController,确保只有已认证用户能上传:
class Api::V1::UploadsController < DeviseTokenAuth::ApplicationController before_action :authenticate_user! def create # 这里用Active Storage处理上传,你也可以换成CarrierWave等 @upload = current_user.uploads.create(upload_params) if @upload.save render json: @upload, status: :created else render json: @upload.errors, status: :unprocessable_entity end end private def upload_params params.require(:upload).permit(:image) # 对应前端上传的字段名 end end
这样就能让react-fine-uploader带着合法的认证信息和后端通信,完成已认证用户的图片上传了。
内容的提问来源于stack exchange,提问作者Don Giulio
相关产品推荐
相关产品推荐

