在跨域情况下,处理 cookie 和 session 的方式取决于具体的需求和限制。下面是两种常见的跨域解决方案:
前后端分离:将前端和后端分别部署在不同的域名下,例如前端部署在 frontend.example.com,后端部署在 backend.example.com。
CORS:在后端服务器的响应中设置合适的 CORS 头部信息,允许前端域名下的跨域请求携带 cookie。
例如,后端服务器返回以下响应头部信息:
Access-Control-Allow-Origin: http://frontend.example.com
Access-Control-Allow-Credentials: true
在前端代码中,通过设置 withCredentials 为 true,使跨域请求能够携带 cookie:
fetch('http://backend.example.com/api', {
credentials: 'include',
})
.then(response => response.json())
.then(data => {
// 处理响应数据
})
.catch(error => {
// 处理错误
});
在同一个域名下部署一个代理服务器