koa设置跨域访问以及跨域验证cookie

2017-09-11  本文已影响0人  名字还是土一点好

环境

解决跨域访问

koa加上如下代码:


app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', ctx.headers.origin); // 很奇怪的是,使用 * 会出现一些其他问题
  ctx.set('Access-Control-Allow-Headers', 'content-type');
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS,GET,HEAD,PUT,POST,DELETE,PATCH')
  await next();
});

解决跨域验证cookie失败

问题描述

在发送跨域请求时,浏览器默认不允许其他域发送cookie。

mk

request 的 credentials属性表示是否允许其他域发送cookie

解决

后端加上:

ctx.set('Access-Control-Allow-Credentials', true);

前端加上:

axios

axios({
  url: url,
  method: method,
  data: data,
  withCredentials: true // 允许跨域发生cookie
})

jquery

$.ajax({
  url: url,
  type: type,
  data: data,
  xhrFields: {
    withCredentials: true
  },
  success: function (data) {
    console.log(data)
  }
})
上一篇 下一篇

猜你喜欢

热点阅读