vue基於proxy實現服務器反向代理功能


測試時使用的時vue-cli:3.0,只在測試環境中使用,正式環境下還是需要使用nginx

在vue-config.js文件中配置

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

module.exports = {
  // 基本路徑
  publicPath:"./",  // 可以設置成相對路徑,這樣所有的資源都會被鏈接為相對路徑,打出來的包可以被部署在任意路徑
  outputDir:"dist",  //打包時生成的生產環境構建文件的目錄
  assetsDir: 'public',  // 放置生成的靜態資源 (js、css、img、fonts) 的 (相對於 outputDir 的) 目錄
  devServer: {
    proxy: {
        '/api': {     //這里最好有一個 /
            target: 'http://192.168.1.109',  // 后台接口域名
            // ws: true,        //如果要代理 websockets,配置這個參數
            // secure: false,  // 如果是https接口,需要配置這個參數
            changeOrigin: true,  //是否跨域
            pathRewrite:{
                '^/api':''
            }
        }
    }
  },
  configureWebpack: {
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            warnings: false,
            compress: {
              pure_funcs: ["console.log", "console.debug"], //移除console
            },
          },
        }),
      ],
    },
  },
};

在調用接口時寫法

async created() {
    var {data: res} = await this.$http.post(`/wechat/parentMsglist`)
    console.log(res)
  },

建議配置axios請求根路徑

import axios from 'axios'
axios.defaults.baseURL = /api'

如果出現報錯,需要在package.json文件中配置

"scripts": {
    "start": "node index.js",
    "server": "nodemon index.js --ignore client"
  },


免責聲明!

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



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