zl程序教程

您现在的位置是:首页 >  后端

当前栏目

前端解决跨域的方法

2023-09-11 14:16:33 时间

跨域:当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域 。

由于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port )。

一.cors 

不用动前端,需要后端加相应头,需要麻烦后端

二.JSONP

通过script的src来解决的,引入外部资源不受同源策略影响,很少用到,只能解决get请求,不能post put请求等,面试问的比较多。

三.代理服务器

①利用nginx反向代理来解决,学习成本高,需要懂后端知识

②vue-cli开启代理服务器(推荐)

vue-cli开启代理服务器方式1:

在vue-cli项目中的vue.config.js文件夹中  开启代理服务器。

缺点:①不能配置多个代理 ②不能灵活的控制走不走代理

module.exports={
  pages:{
    index:{
      //入口
      entry:'src/main.js',
    },
  },
  lintOnSave:false, //关闭语法检查
  // 开启代理服务器
  devServer:{
    proxy:'http://localhost:5000'
  }
}

直接请求8080

    axios.get('http://localhost:8080/students').then(
      res => {
        console.log('请求成功', res);
      },
      error => {
        console.log('请求失败', error.message);
      }
    )

vue-cli开启代理服务器方式2:

解决了可以加多个代理服务器

module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
  lintOnSave: false, //关闭语法检查 
  // 开启代理服务器
  devServer: {
    proxy: {
      //匹配所有以/api开头的请求路径 
      '/api': {
        target: 'http://localhost:5000',
        //正则表达式把api头去掉,再请求
        pathRewrite: { '^/api': '' },
        //用于支持websocket
        ws: true,
        //用于控制请求头中的host值,为true时,服务器收到的请求头中的host为:localhost:5000,false时为localhost:8080
        changeOrigin: true
      },
      '/demo': {
        target: 'http://localhost:5000',
        pathRewrite: { '^/demo': '' },
        ws: true,
        changeOrigin: true
      },
    }
  }
}

请求:

    axios.get('http://localhost:8080/api/students').then(
      res => {
        console.log('请求成功', res);
      },
      error => {
        console.log('请求失败', error.message);
      }
    )


    axios.get('http://localhost:8080/demo/students').then(
      res => {
        console.log('请求成功', res);
      },
      error => {
        console.log('请求失败', error.message);
      }
    )

------------vue3跨域问题------------

axios.get("path/api/mmdb/movie/v3/list/hot.json?ct=%E9%95%BF%E6%B2%99&ci=70&channelId=4").then((res)=>{
   console.log(res)
})

vite.config.js中配置中转服务器

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: { //中转服务器
    proxy: { //通过代理实现跨域
      '/path': {
        target: 'https://i.maoyan.com',  //替换的服务器地址
        changeOrigin: true,  //开启代理,允许跨域
        rewrite: path => path.replace(/^\/path/, '')  //设置重写的路径
      }
    }
  }
})