新手问题 Rails + Nextjs 问题

perish · 2025年02月09日 · 最后由 mechiland 回复于 2025年02月10日 · 273 次阅读

陈金洲 - Rails + Next.js:一种提升开发者和用户体验的开发架构范式 - RubyConf China 2024

本地环境:

  • Ruby on Rails 版本:8.0.0
  • Nextjs 版本:15.1.6

rails 中的验证通过 authenticate 自动生成,其他都如上述视频中设置,但是 nextjs 请求登录,在浏览器中没有对应响应的 cookie,确认后端已经生成了对应的 session 记录; 不知道有没有其他人试过视频中的方案遇到过这个问题没有?求大佬解惑!!!

假设 Rails 正常运行在 localhost:3000, Next.js 运行在 localhost:3001

1. 确认通过 http://localhost:3000 能够正常登录

  • 假设登录地址为 POST /session
  • 在 Chrome Console 中能够看到 cookie (_xxx_session)

2. 确认在 Next.js 中,next.config.mjs 配置正确:

看看 URL Rewrite 是否包含类似的配置:

const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: `http://localhost:3000/:path*`,
      },
    ];
  },
};

export default nextConfig;

3. 尝试通过 Postman 之类的 API 测试工具,使用同样的用户名密码访问 Next.js 转发的 API:

POST /api/session

注意看 Next.js console 和 Rails console

如果正确,那么 Postman 中应该会拿到返回的 session token


演讲中提到的参考代码:

需要 登录 后方可回复, 如果你还没有账号请 注册新账号