0

如题,写了一个后端转发的模块,发现设置的cookie无效,查看控制台响应头中也没有Set-cookie,手动设置Set-cookie也是不行,请帮忙看一下是哪里配置的有问题吗?

function parseSetCookie(cookie){
  var options = cookie.split(';')
  var [key, val] = options.shift().split('=')
  var result = { key, val, options: {} }
  for(let i=0, len=options.length; i < len; i++){
    let [option, optionVal] = options[i].trim().split('=')
    option = option.replace(/./, function(s){ return s.toLowerCase() })
    if(['domain', 'secure'].includes(option)){ continue }
    result.options[option] = optionVal || true
  }

  return result
}

module.exports = function(req, res){
  var {
    body: {url, data, timeout = 7000},
    cookies = {}
  } = req

  axios({
    method: 'post',
    url, data, timeout,
    headers: {
      cookies: Object.keys(cookies).map(function(key){
        return `${key}=${cookies[key]}`
      }).join(';')
    },
    
    transformRequest (data){
      return Object.keys(data).map(function(key){
        return `${key}=${data[key]}`
      }).join('&')
    }
  }).then(function(resData){
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Credentials', 'true')
    if('set-cookie' in resData.headers){
      for(let i=0, len=resData.headers['set-cookie'].length; i < len; i++){
        let cookie = parseSetCookie(resData.headers['set-cookie'][i])
        res.cookie(cookie.key, cookie.val, cookie)
        console.log(res)
      }
    }
    res.send(resData.data)
  }, function(e){
    res.sendStatus(408)
  }).catch(function(){
    res.sendStatus(500)
  })
}
23 小时前提问
0 个回答

撰写答案

推广链接