利用vue-cli解决跨域问题

解决跨域的方法

跨域时浏览器能拿到数据,只是没有给到你

  1. 后端配置CROS(后端返回数据时带请求头使浏览器不认为是跨域)
  2. JSONP
  3. 代理服务器
    • vue-cli提供的代理服务器
    • 发送ajax请求先经过8080代理服务器,再去请求5000服务器
    • 服务器直接不用ajax所有没有跨域
    • 8080与代理服务器处于同协议域名端口,所有没有跨域

image.png

模拟跨域解决流程

  1. 开启服两台服务器 http://localhost:5000/http://localhost:5001/
  2. node启动 http://localhost:8080/往5000和50001请求数据
  3. 出现跨域问题,因为端口号不同
  4. 配置代理-获取数据

    配置代理解决跨域

    代理一般都是开发使用,生成环境不用

    方法一

在vue.config.js中添加如下配置:

  1. devServer:{
  2. proxy:"http://localhost:5000"
  3. }

使用

  1. //代理服务器默认会先去找你服务器有的的东西 所有下边两个会去找文件
  2. axios.get('http://localhost:8080/test.txt') //这样写会从文件夹中寻找test.txt文件
  3. axios.get('http://localhost:8080/students') //这样写会从文件夹中寻找students文件(不带后缀名)
  4. axios.get('http://localhost:8080/students') //获取5000students数据

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

方法二

webpack

编写vue.config.js配置具体代理规则:

  1. module.exports = {
  2. devServer: {
  3. proxy: {
  4. '/api1': {// 匹配所有以 '/api1'开头的请求路径
  5. target: 'http://localhost:5000',// 代理目标的基础路径
  6. changeOrigin: true,
  7. pathRewrite: {'^/api1': ''}
  8. },
  9. '/api2': {// 匹配所有以 '/api2'开头的请求路径
  10. target: 'http://localhost:5001',// 代理目标的基础路径
  11. changeOrigin: true,
  12. pathRewrite: {'^/api2': ''}
  13. }
  14. }
  15. }
  16. }
  17. /*
  18. changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  19. changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  20. changeOrigin默认值为true
  21. */

发送请求:

  1. //http://localhost:8080 必须带 或者配置baseurl
  2. getStudents(){
  3. axios.get('http://localhost:8080/api1/students').then(
  4. response => {
  5. console.log('请求成功了',response.data)
  6. },
  7. error => {
  8. console.log('请求失败了',error.message)
  9. }
  10. )
  11. },
  12. getCars(){
  13. axios.get('http://localhost:8080/api2/cars').then(
  14. response => {
  15. console.log('请求成功了',response.data)
  16. },
  17. error => {
  18. console.log('请求失败了',error.message)
  19. }
  20. )
  21. }

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

    Vite

    配置代理

    vite.config.js中添加如下配置: ```javascript //调用 //axios.defaults.baseURL = ‘/api’ //data = await $http({‘url’:’/one/data’});

import path from ‘path’ export default defineConfig({ server: { proxy: { ‘/api’: { target: ‘http://localhost:8888‘, //代理到目标地址 changeOrigin: true, //设置访问目标地址允许跨域 rewrite: (path) => path.replace(/^\/api/, ‘’), } } } })

  1. <a name="eRKXN"></a>
  2. #### 环境变量
  3. 代理一般都是开发使用,生成环境不用。在vite中`import.meta.env.DEV`环境变量跨域判断开发(true)或生产环境(false)
  4. > vite.config.ts 配置代理
  5. ```json
  6. server: {
  7. proxy: {
  8. // 正则表达式写法
  9. '^/A': {
  10. target: 'http://120.24.64.5:8088',
  11. changeOrigin: true,
  12. rewrite: (path) => path.replace(/^\/A/, '')
  13. },
  14. '^/B': {
  15. target: 'http://192.168.1.2',
  16. changeOrigin: true,
  17. rewrite: (path) => path.replace(/^\/B/, '')
  18. }
  19. }
  20. }

src/api/index.ts 编写接口

//利用环境变量设置不同环境下url信息
let preFn = function (prepath: string) {
  return import.meta.env.DEV ? prepath : ''
};

//该接口匹配A同事解决跨域 并在生产环境中去除/A
export const adminLogin = () => request.post(preFn('/A')+'/admin/login')
//该接口匹配B同事解决跨域 并在生产环境中去除/B
export const adminInfo = ()=> request.get(preFn('/B')+'/admin/info')

如果env报错,tsconfig.json添加 "compilerOptions": {"types": ["vite/client"]} 具体看https://www.cnblogs.com/wisewrong/p/15971158.html