Axios 跨域客户端有个配置需要注意:withCredentials 这个配置如果是ture,表示发送的ajax请求里面带cookie,但同时也会拒绝服务端的'Access-Control-Allow-Origin','*'配置星的做法,原因是安全问题。

解决办法

  1. 如果你的系统依赖cookie,则withCredentials还是需要开启为true,但服务端就需要修改Access-Control-Allow-Origin配置到支持ajax请求的域,然后再配置上"Access-Control-Allow-Credentials", "true"

  1. 如果你的系统不依赖cookie,则只需要把withCredentials关掉,注释即可,服务端还是按配置Access-Control-Allow-Origin:"*"

 app.use(async (ctx, next) => {
    //ctx.set('Access-Control-Allow-Origin','http://xx:8080')
    //ctx.set("Access-Control-Allow-Credentials", "true");
    ctx.set('Access-Control-Allow-Origin','*')
    ctx.set('Access-Control-Allow-Headers','Content-Type,Content-Length,Authorization,Accept,X-Requested-With')
    ctx.set('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS')
    
  await next()
  // 允许所有跨域
  if (ctx.request.method === 'OPTIONS') {
    console.log('跨域请求')
    ctx.response.status = 200
    ctx.response.message = 'OK'
  }
})
  1. 如果系统依赖cookie,又想支持全域,可以通过以下方式处理,但安全性肯定是差。第一步前端的withCredentials还是开启为true,服务端的跨域配置这么写

 app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin',ctx.request.headers.origin)
    ctx.set("Access-Control-Allow-Credentials", "true");
    //ctx.set('Access-Control-Allow-Origin','*')
    ctx.set('Access-Control-Allow-Headers','Content-Type,Content-Length,Authorization,Accept,X-Requested-With')
    ctx.set('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS')
    
  await next()
  // 允许所有跨域
  if (ctx.request.method === 'OPTIONS') {
    console.log('跨域请求')
    ctx.response.status = 200
    ctx.response.message = 'OK'
  }
})

从请求头拿orgin

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐