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;
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM