s

vue/vite 开发模式和生产模式 跨域配置

【vue.config.js 或者 vite.config.js 中配置】  server: {
    // proxy: { //server 开启, 生产模式
    //   '/api': {
    //     changeOrigin: true,
    //     target: 'http://yourdomain:9504',
    //     // rewrite: (path) => path.replace(/^\/tp5\/index\/rsdemo/, '')
    //   }
    // },
    proxy: {
      '/tp5/index/rsdemo': { // 开发模式  ,后面请求 就需要带上 这一字符串
        changeOrigin: true,
        target: 'http://localhost:8999' // http:// 不可少, 如果只写 localhost:3001 代理会失败
      }
    }
  }

  axios:

import axios from 'axios';

const instance = axios.create({ // 创建实例
  timeout: 10000,
  baseURL: '/tp5/index/rsdemo' //localhost
  // baseURL: '/api' // 175 server 开启
})

useage:

  const server = '/point/getPoints'
  const local = '/getPoints'
  const {
    data: data
  } = await proxy.$axios.post(local, { // 这里把axios配置为全局api了 
    'belongTo': path,
  });
但是需要注意的是,这个跨域只针对开发模式有效,一旦打包之后,前端配置的跨域就不起作用了,打包后就必须部署在web服务器上,脱离了 vue的代理配置。
如果是部署在nginx上,反向代理配置如下:
    server {
        listen       3000;
        server_name  localhost;

        location / {
            root   D:/phpstudy_pro/WWW/biwDOT/code/biwDot/dist; // 这里是打包生成的dist目录
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        } 
        location /index/rsdemo { // 这里是跨域接口前缀, 当请求地址为 http://localhost:3000/index/rsdemo/xxx 时 就会代理到 http://localhost:8999/index/rsdemo/xxx
           proxy_pass http://localhost:8999;
        }
    }

  

posted @ 2022-02-22 16:15  努力不搬砖的iori  阅读(2771)  评论(0编辑  收藏  举报