跨域解决办法

563 阅读2分钟

出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定 出于安全考虑,防止数据被其他网站轻松获取

同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互

跨域同源(协议、域名、主机(host)、端口号相同),其中任何一个不同都会引起跨域

解决方法

JSONP

JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好(兼容低版本IE),缺点是只支持get请求,不支持post请求。

JSONP实现跨域请求的原理简单的说,就是动态创建<script>标签,然后利用<script>的src 不受同源策略约束来跨域获取数据。

JSONP 由两部分组成:回调函数和数据。回调函数是当响应到来时应该在页面中调用的函数。回调函数的名字一般是在请求中指定的。而数据就是传入回调函数中的 JSON 数据。

动态创建<script>标签,设置其src,回调函数在src中设置:

前端Vue开发模式跨域

vue.config.js 文件中加入proxy设置

devServer: {
   port: 4399,
   host: "localhost",
   https: false,
   open: true,// vue项目启动时自动打开浏览器
   // hotOnly: true, // 热更新
   // overlay: { // 让浏览器 overlay 同时显示警告和错误
   //     warnings: true,
   //     errors: true
   // },
   proxy: {
      "/api/": { // 是代理标识,用于告诉node,url前面是/api的就是使用代理的
         target: "http://localhost:4399",//目标地址,一般是指后台服务器地址
         changOrigin: true, //是否跨域允许开启代理,创建虚拟服务端
         pathRewrite: {// pathRewrite 的作用是把实际Request Url中的'/api'""代替
            "^/api": ''
         }
      }
   }
},

node后端 cors

// CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

后端服务可以开启跨域允许


const urlArray = [    'http://localhost:4399',    'http://localhost:4400',    'http://127.0.0.1:4401',    'http://localhost:4402',    NGINX_URL,    NGINX_URL_TLS];

app.use(cors({
    origin: function (ctx) {
        // let url = ctx.header.referer.substr(0,ctx.header.referer.length - 1);
        console.log(ctx.url);
        console.log('cors',ctx);
        // return urlArray
        return "https://localhost.cn:443"
    },
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
}))

image.png

nginx跨域

nginx反向代理请求到后端允许访问的地址上,就变相的解决了跨域问题。同时也便于管理,和服务器安全问题。 nginx可以像一个网关一样代理各种不同的业务需求

location ^~/api/ { 
    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header X-Forworded-For $proxy_add_x_forwarded_for; 
    proxy_pass http://localhost:4399/; #这里的后端接口地址 
}

nginx配置文章链接: juejin.cn/post/706963…