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