跨域解决方法二
- 跨域解决方法一(jsonp)
- 跨域解决方法三(代理服务)
- CORS(Cross-origin resource sharing),跨域资源共享,是一份浏览器技术的规范,用来避开浏览器的同源策略。它是W3C的标准,是AJAX请求的根本解决方法。
CORS跨域设置
解决跨域设置
- node.js服务环境,需要在服务端设置
ctx.set('Access-Control-Allow-Origin', '*');
//允许任意域名都可以访问,默认不能携带cookie。ctx.set('Access-Control-Allow-Origin','http://localhost:8082');
//只允许http://localhost:8082访问- 白名单方式
let whiteList = [ 'http://localhost:8082', 'http://localhost:8083', 'http://localhost:9999' ] app.use(async (ctx,next) => { let requestOrigin = ctx.header.origin; if(whiteList.includes(requestOrigin)){ ctx.set('Access-Control-Allow-Origin',requestOrigin); } if(ctx.method.toLowerCase() == 'options'){ ctx.set('Access-Control-Request-Method','GET,OPTIONS,POST'); ctx.body = ''; return; } await next(); })
其他设置
ctx.set('Access-Control-Request-Method','GET,OPTIONS,POST')
//设置允许请求的方式Access-Control-Allow-Headers
:允许requset设置的头部ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
Access-Control-Expose-Headers
:允许客户端获取的头部keyctx.set('Access-Control-Expose-Headers','Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')