前端服务器代理 Proxy

跨域资源请求

Vue资源服务器请求遇到常见的跨域资源请求时A-C-A-O,用Vue脚手架搭建的其实也是Node服务器环境.运行时仅仅只是将项目打包至内存环境下,然后浏览器运行该项目.若后端没有使用Cors中间件.则可以使用Proxy.


根目录创建 vue.config.js

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。

具体配置信息

module.exports={

  代理一个服务器
  devServer:{
    proxy: 'http://localhost:3000',  ->告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:3000。
    host: '0.0.0.0',
    port: 8003,                                ->本地    
    open: true,  
    https: false,                        
    proxy: null, // string | Object
  },
  lintOnSave:false, //关闭esling警告
  lintOnSave: process.env.NODE_ENV !== 'production', //生产构建时禁用
  productionSourceMap:false, //打包不携带map文件

  cli3 代理多个服务器
  proxy:{//代理是从指定的target后面开始匹配的,不是任意位置;配置pathRewrite可以做替换
    '/api':{//axios访问 /api == target + /api
      target:'https://localhost:3000',
      changeOrigin:true,//创建虚拟服务器
      ws:true,//websocket代理
    },
    '/douban':{// axios 访问 /douban == target + '/douban'
      target:'https://api.douban.com',
      changeOrigin:true,
      pathRewrite:{//路径替换
        '^/douban':'',// axios 访问/douban/v2 == target + /v2
      }
    }
  }
}

官方文档

devServer.proxy

  • Type: string | Object

    如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

    devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:

    module.exports = {
      devServer: {
        proxy: 'http://localhost:4000'
      }
    }

    这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000

    如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象。完整的选项可以查阅 http-proxy-middleware 。

    module.exports = {
      devServer: {
        proxy: {
          '/api': {
            target: '<url>',
            ws: true,
            changeOrigin: true
          },
          '/foo': {
            target: '<other_url>'
          }
        }
      }
    }

参考:https://github.com/vuejs/vue-cli/tree/dev/docs/zh/config
   https://webpack.js.org/configuration/dev-server/

posted @ 2019-11-02 15:32  Scok  阅读(9879)  评论(1编辑  收藏  举报