Vue 前端项目配置代理解决跨域问题

Vue 前端项目配置代理解决跨域问题

更新VueCli4.5 下的配置

问题如下,经常在本地调试接口出现这种问题

问题描述

解决方式1:Chrome 的扩展插件

  • 以前使用Chrome 的扩展插件,但是有时候还是会出现莫名其妙的问题。
  • 需要梯子才行 Allow CORS: Access-Control-Allow-Origin

解决方式2:服务端配置跨域访问

  • 也可以在服务端配置解决这个问题,这个要找后台协商。
  • 很多开源的第三方库都做了处理,你在哪里调用都不会出现跨域问题。

解决方式3:前端项目配置本地代理

  • webpack 3.6
  • 经过测试,这种方式通用性很强,不需要知道服务器有没有配置跨域,浏览器有没有装插件,都可以访问外部接口。
  • Vue项目中 config/index.js
module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/api': {
                target: 'https://1.2.3.4:89', // 接口地址
                changeOrigin: true, // 是否跨域
                pathRewrite: { 、// 转发
                    '^/api': ''
                },
                secure: false 
            },
        }
}
  • src/api/index.js 中如下配置 baseURL
const debug = process.env.NODE_ENV !== 'production'
const axInstance = axios.create({
    baseURL: debug ? 'api' : 'http://1.3.4.5.6:89',
    timeout: 10000,
    responseType: 'json',
    withCredentials: false, // 表示跨域请求时是否需要使用凭证
    headers: {
        token: store.state.axios.token,
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
})
  • 配置完毕后,运行项目,访问接口 http://0.0.0.0:8080/api/getinfo 就会被转发到 https://1.2.3.4:89/getinfo

VueCli4.5下的配置

  • 修改vue.config.js 文件,添加proxy
const path = require("path");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
module.exports = {
  devServer: {
    // overlay: { // 让浏览器 overlay 同时显示警告和错误
    //   warnings: true,
    //   errors: true
    // },
    open: false, // 是否打开浏览器
    // host: "localhost",
    // port: "8081", // 代理断就
    https: false,
    hotOnly: true, // 热更新
    proxy: { // 配置本地代理
      "/api": {
        // target:'http://192.383.2.2:89',
        secure: false,
        changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
        // ws: true, // 是否启用websockets
        pathRewrite: {
          "^/api": "/",
        },
      },
    },
  }
}
posted @ 2020-04-26 22:00  struggle_time  阅读(18110)  评论(0编辑  收藏  举报