前后端分离项目koa2设置cookie无效

lhuanyu
  • 60

前端项目在3000端口,后端项目在9527端口,跨域是用koa2-cors做的如下:

app.use(cors({
    origin: function () {
        return 'http://localhost:3000';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'], //设置允许的HTTP请求类型
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

koa2设置cookie的代码:

  async signIn( ctx ){
    let formData = ctx.request.body
    let result = {
      success: false,
      message: '',
      data: null,
      code: ''
    }
    let userResult = await userInfoService.signIn( formData )
      console.log(userResult)
    if ( userResult ) {
      if ( formData.userName === userResult.user_name ) {
          ctx.cookies.set(
              'cid',
              userResult.user_id,
              ckConfig
          )
        result.success = true
          console.log(ctx.cookies)
      } else {
        result.message = userCode.FAIL_USER_NAME_OR_PASSWORD_ERROR
        result.code = 'FAIL_USER_NAME_OR_PASSWORD_ERROR'
      }
    } else {
      result.code = 'FAIL_USER_NO_EXIST',
      result.message = userCode.FAIL_USER_NO_EXIST
    }
    ctx.body = result;
  }

响应如下:为什么没有set-cookie响应头

clipboard.png

clipboard.png

回复
阅读 3.1k
2 个回答

前端接口请求设置一下ajax的withCrendetails属性试试,跨域默认不让操作cookie的,补充上这个属性应该就好了
vue-resource

Vue.http.options.credentials = true

用axios时,可以在拦截器中设置如下

axios.interceptors.request.use((config) => {
    config.withCredentials = true
    return config
}, (error) => {
    return Promise.reject(error)
})

clipboard.png
将项目放在nginx上也不行。

宣传栏