CORS跨域设置

CORS跨域设置

CORS(Cross-origin resource sharing),跨域资源共享,是⼀份浏览器技术的规范,⽤来避开 浏览器的同源策略 简单来说就是解决跨域问题的除了jsonp外的另⼀种⽅法;⽐jsonp更加优雅。

  • 1.(‘Access-Control-Allow-Origin’, ‘*’) //这个表示任意域名都可以访问,默认不能携带 cookie了。(必须字段)
res.header('Access-Control-Allow-Origin', 'http://www.baidu.com'); //这样写,只有 www.baidu.com 可以访问。
 res.header('Access-Control-Allow-Origin', '*'); //这个表示任意域名都可以访问。
  • 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') 

CORS请求时, XMLHttpRequest 对象的 getResponseHeader() ⽅法只能拿到6个基本字段: CacheControl 、 Content-Language 、 Content-Type、 Expires 、 Last-Modified 、 Pragma 。如果想拿到其 他字段,就必须在 Access-Control-Expose-Headers⾥⾯指定。

  • 3000端口前端页面
    < script>
    document.querySelector(".btn1").onclick =function(){
    let xhr = new XMLHttpRequest();
    xhr.open(“post”,"/post",true);
    // xhr.setRequestHeader();
    xhr.onload = function(){
    console.log(xhr.responseText);
    }
    xhr.send();
    }

    document.querySelector(".btn2").onclick = function(){
    //跨域: 请求成功了
    //跨域是浏览器行为
    let xhr = new XMLHttpRequest();
    xhr.open(“post”,“http://localhost:4000/post”,true);
    // xhr.setRequestHeader();
    xhr.onload = function(){
    console.log(xhr.responseText);
    //获取返回头部信息
    let res = xhr.getAllResponseHeaders();
    console.log(res);
    }
    xhr.send();
    }

< /script>

  • 4000端口后端
    router.post("/post",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.允许前端设置的头部

    //4.设置允许前端发送的请求方式

    ctx.body= “4000端口–非同源”;
    });

发布了42 篇原创文章 · 获赞 0 · 访问量 877

猜你喜欢

转载自blog.csdn.net/cybcc/article/details/105471391