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

使用Axios调用Directus时Set-Cookie无法生效的问题排查

问题:Cookie模式下Directus登录后无法生成访问Cookie

我的应用运行在localhost:8080,Directus(一款无头CMS)实例通过Docker部署在localhost:8055。我尝试以cookie模式从应用向Directus发起API调用,按预期使用正确凭证完成登录请求后,响应头应包含Set-Cookie字段以在浏览器中创建访问Cookie,但该Cookie始终未生成。

以下是我使用的登录调用代码:

const directusOptions = {
  email: 'email@domain.com',
  password: 'admin123456',
  mode: 'cookie'
}

await axios.post('http://localhost:8055/auth/login', directusOptions)
  .then(response => response)
  .catch(error => console.error(error.message))
问题排查与解决方法
  • 跨域请求未携带凭证:浏览器同源策略会限制跨域Cookie的设置,axios默认不会在跨域请求中携带凭证。需要在请求中添加withCredentials: true配置,修改后代码如下:
const directusOptions = {
  email: 'email@domain.com',
  password: 'admin123456',
  mode: 'cookie'
}

await axios.post('http://localhost:8055/auth/login', directusOptions, {
  withCredentials: true
})
  .then(response => response)
  .catch(error => console.error(error.message))
  • Directus跨域配置缺失:Docker部署的Directus需要正确配置跨域允许凭证。在Directus的环境变量中添加以下配置,然后重启Docker容器使设置生效:

    • PUBLIC_URL=http://localhost:8055
    • CORS_ENABLED=true
    • CORS_ORIGIN=http://localhost:8080
    • CORS_CREDENTIALS=true
  • Cookie SameSite属性限制:如果Directus设置的Cookie SameSite属性为Strict或Lax,跨域场景下浏览器可能不会存储Cookie。可检查Directus的SESSION_COOKIE_SAMESITE环境变量,将其设置为None(注:生产环境需配合HTTPS使用,本地开发可暂时忽略该限制)。

  • 端口差异导致的同源问题:即使都是localhost,不同端口仍属于不同源,必须确保跨域配置完全匹配应用的Origin,同时开启凭证允许选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:07:07