You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7 API会话Cookie已设置但后续请求未携带问题排查

问题解决方案

1. 让Chrome/Firefox保存并自动携带Cookie的配置

  • 修正Cookie的Domain属性:将Rails中Cookie的domain设为.localhost(而非localhost:3000),这样同一主域下的不同端口(3000和8080)可共享Cookie。
  • 配置Cookie的SameSite属性:开发环境下设置为:lax(生产HTTPS环境可改为:none并搭配secure: true,但localhost的HTTP环境下secure: true会导致Cookie无法保存)。
  • 验证浏览器Cookie存储:打开开发者工具(Chrome按F12),进入「Application」→「Cookies」→「http://localhost:3000」,确认_interslice_session是否存在。若不存在,检查响应头的Set-Cookie是否包含Domain=.localhost、SameSite=Lax,且无Secure属性(HTTP环境下)。

2. Flutter Web请求需设置的参数

Flutter Web发起跨域请求时,必须开启携带凭证配置,浏览器才会自动附加Cookie:

  • 使用http包时,在请求中添加withCredentials: true:
    import 'package:http/http.dart' as http;
    
    final response = await http.get(
      Uri.parse('http://localhost:3000/api/your-endpoint'),
      withCredentials: true, // 关键配置
    );
    
  • 使用dio包时,全局或单个请求开启withCredentials:
    import 'package:dio/dio.dart';
    
    final dio = Dio();
    dio.options.withCredentials = true; // 全局开启
    
    // 单个请求也可单独设置
    final response = await dio.get('http://localhost:3000/api/your-endpoint',
        options: Options(withCredentials: true));
    

无需手动设置Cookie请求头,浏览器会自动处理。

3. Rails配置的问题修正

你的配置存在两处需要调整的地方:

Session存储配置修正

修改config/application.rb中的session_store配置,调整domain并添加SameSite属性:

config.session_store :cookie_store, 
  key: '_interslice_session', 
  domain: '.localhost', # 改为通配localhost主域
  same_site: :lax # 开发环境用lax,生产HTTPS可改为:none并加secure: true
config.middleware.use ActionDispatch::Cookies
config.middleware.use config.session_store, config.session_options

CORS配置修正

config/initializers/cors.rb中methods存在拼写错误,:path应为:patch:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:8080'
    resource '*',
    headers: :any,
    credentials: true,
    methods: [:get, :post, :options, :put, :patch] # 修正path为patch
  end
end

另外,可通过rails middleware命令查看中间件加载顺序,确认ActionDispatch::Cookies和ActionDispatch::Session::CookieStore在列表中。


内容的提问来源于stack exchange,提问作者Abhinav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:10:25