nginx获取request中的cookie并在response中返回

开发时,遇到一个棘手问题,调用别人的接口,但是需要将request中的cookie作为参数传递。

由于我们域名下的 cookie httpOnly属性为 true,所以前端无法使用 document.cookie 获取。

找到的解决方案有:

一、通过后台接口获取cookie【我想出来的方案】

        后台获取到$_REQUEST中的cookie,并从接口返回给前端

二、通过配置nginx作为响应头传递【领导还是你领导,赞👍】

    location ^~ /yjymoa/itsm/api {
        proxy_pass http://1.2.3.4/api;
        proxy_connect_timeout 300;
        proxy_read_timeout 300;
        proxy_send_timeout 300;
        add_header THC $http_cookie;   #此处为重点
        add_header Access-Control-Allow-Origin '*';
    }

 前端使用的是"umi-request"封装的请求,所以需要进行响应拦截


// 添加 request 拦截器
request.interceptors.request.use((url, options) => {
  const token = getToken();
  const currentUser = getCurrentUser();
  const config = { url, options };

  // 添加 token
  if (token) {
    config.options.headers.Authorization = `Bearer ${token}`;
  }
  // 添加当前角色
  // if (currentUser && currentUser.currentRole) {
  //   // 因为currentRole存的是前端的命名所以要通过MAP解析出后台的值
  //   config.options.headers[HTTP_ROLE_HEADER] = _.invert(SERVER_ROLES_MAP)[currentUser.currentRole];
  // }

  return config;
});

// response拦截器, 处理response
request.interceptors.response.use((response, options) => {
  let cookie = response.headers.get("THC");
  if (cookie && response.url.indexOf('sso') > -1) {
    window.localStorage.setItem('COOKIE_KEY', cookie);
  }
  return response;
});


// 使用时可以直接get获取了
window.localStorage.getItem('COOKIE_KEY');

记录一下被自己笨到emo的一天......😈

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值