CORS跨域设置
CORS(Cross-origin resource sharing),跨域资源共享,是⼀份浏览器技术的规范,⽤来避开 浏览器的同源策略 简单来说就是解决跨域问题的除了jsonp外的另⼀种⽅法;⽐jsonp更加优雅。
- 1.(‘Access-Control-Allow-Origin’, ‘*’) //这个表示任意域名都可以访问,默认不能携带 cookie了。(必须字段)
//这个表示任意域名都可以访问。
//问题:1.不安全 2.不能携带凭证
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Origin', 'http://www.baidu.com'); //这样写,只有 www.baidu.com 可以访问。
- 2.Access-Control-Allow-Headers :设置允许requset设置的头部;
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
- 3.Access-Control-Expose-Headers 允许客户端获取的头部key;
('Access-Control-Expose-Headers','Content-Type, Content-Length, Authorization, Accept, X- Requested-With , yourHeaderFeild')
- 4.设置前端允许请求的方法
ctx.set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,HEAD,OPTIONS");
- 5.允许携带凭证
前端
允许跨域请求携带凭证
xhr.withCredentials = true;
后端
ctx.set("Access-Control-Allow-Credentials",true);
- 6.预检请求
1.预检请求 options
2.允许前端设置头部信息
前端
xhr.setRequestHeader("Content-type","application/json");
后端
router.options("/ * ",ctx=>{
//1.允许跨域
// ctx.set("Access-Control-Allow-Origin","*"); // 1.不安全 2.不能携带凭证
ctx.set("Access-Control-Allow-Origin","http://localhost:3000");
//2.允许获取的头部信息;(响应头)
ctx.set("Access-Control-Expose-Headers","Content-Type, Content-Length,Date")
//3.设置前端允许请求的方法;
ctx.set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,HEAD,OPTIONS");
//4.允许前端设置的头部(请求头)
ctx.set("Access-Control-Allow-Headers","Content-Type, Content-Length, Authorization,test");
ctx.set("Access-Control-Max-Age",3600*24);
//5.允许携带凭证
ctx.set("Access-Control-Allow-Credentials",true);
console.log("有预检请求");
ctx.body = "";
});
- 7.设置预检请求的缓存时间
ctx.set("Access-Control-Max-Age",3600*24);