跨域导致cookie丢失。
使用axois发送请求,在服务器端配置了cors:
router.use("/", (req, res, next) => {
console.log(req.headers.origin)
// req.headers.origin
res.header("access-control-allow-origin", req.headers.origin)
res.header("access-control-allow-headers", "content-type")
res.header('Access-Control-Allow-Credentials', true)
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
next()
})
前端的axois配置:
app.config.globalProperties.$http = axios.create({
baseURL: 'http://127.0.0.1:3000',
withCredentials: true,
})
网上查询了相关资料说进行跨域请求需要在前端发送的请求头中配置withCredentials为true,后端在响应头中加入res.header('Access-Control-Allow-Credentials', true)且access-control-allow-origin不能为*,即使这个样子,axois进行跨域请求还是会丢失cookie
你好,关于你提到的axios跨域请求丢失cookie,原因可能如下:
Access-Control-Allow-Origin不能为,这是因为当Access-Control-Allow-Credentials设置为true的时候,Access-Control-Allow-Origin必须指定明确的源(即设置为指定的源,而不是),否则浏览器会拒绝发送该请求。
如果后端服务是基于nodejs的,需要在响应头中加入Access-Control-Allow-Origin和Access-Control-Allow-Credentials字段,并将Access-Control-Allow-Origin设置为当前请求的origin。此外还需要添加Origin请求头作为允许跨域请求的条件之一。
如果前端请求中使用了axios.defaults.withCredentials = true来设置全局withCredentials,那么单个请求中就不需要再设置这个属性了。直接发送带有cookie的请求即可。
综上所述,你可以参照以下代码进行设置:
后端配置:
router.use("/", (req, res, next) => {
const { origin } = req.headers;
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Credentials", true);
next();
});
前端配置:
app.config.globalProperties.$http = axios.create({
baseURL: 'http://127.0.0.1:3000',
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Origin": "http://localhost:8080"
}
})
如果以上方法还无法解决cookie丢失问题,可以根据实际情况进一步排查。可能是由于浏览器安全策略导致的,比如禁止第三方Cookie、浏览器隐身模式等等。