前端cookie跨域注意点

前端 2021-03-22 3473

​前端跨域时,会涉及到cookie的跨域问题,当你发现跨域已经正常,但是set-cookie就是不起作用时,你可以从以下2个方向来解决

1.cookie的域与当前命名不匹配
如cookie的域名为huyu.info

Set-Cookie: xxx=6666; path=/; expires=Mon, 22 Mar 2021 14:33:39 GMT; domain=huyu.info

但你的访问域名为http://127.0.0.1:8000,这时出现跨域,set-cookie就不起作用

你可以采用:

1.将domain去除,此时cookie的域将是你的访问地址的域

2.使用nginx代理

location /api {
   proxy_pass https://b.test.com;
   proxy_cookie_domain b.test.com  a.test.com;
} 

proxy_cookie_domain参数的作用是转换response的set-cookie header中的domain选项,由后端设置的域名domain转换成你的域名replacement,来保证cookie的顺利传递并写入到当前页面中,注意proxy_cookie_domain负责的只是处理response set-cookie头中的domain属性

如果你使用服务器跨域,你可以这样做(关于如何设置服务端跨域,你可以查看之前的文章):

安装

cnpm install http-proxy-middleware --save

此包中,有cookieDomainRewrite配置,可以方便实现上面替换cookie的操作

ctx.body = createProxyMiddleware({
      target: 'https://www.yun.cn', // 服务器地址
      changeOrigin: true,
      secure: false,
      "pathRewrite": {
        "^/auth": ""
      },
      cookieDomainRewrite: {
        '.yun.cn': '127.0.0.1'
      }
})

2.前后端配置
服务器代理解决跨域时,你需要配置

服务的响应头需要配置Access-Control-Allow-Credentials并且为true。
响应头中的Access-Control-Allow-Origin一定不能为*,必须是指定的域名
前端配置浏览器发起ajax需要指定withCredentials 为true
以koa和axios为例子:

const Koa = require('koa');
const {createProxyMiddleware} = require('http-proxy-middleware');

const app = new Koa();
const cors = require('koa2-cors');
//跨域代理
app.use(cors({
  origin: 'http://127.0.0.1:8080',
  maxAge: 2592000,
  credentials: true
}));

前端axios

import axios from 'axios'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
  withCredentials: true
})

另外要注意的一件事,在配置和访问注意localhost和127.0.0.1不是一个东西!这坑了我几个小时

crying

标签:前端

文章评论

评论列表

已有0条评论