前端开发中网络代理的配置

135 阅读3分钟

前端开发中,少不了碰到跨域(同源策略)的问题,这时我们就要解决这个问题。一般这个问题可以在后台代码加入代码的方式解决,或者前端我们自己解决。此处我们就讨论前端怎么解决这个问题。

有两种配置解决:

1.单一代理,这种配置统一配置,全局生效。

React项目(脚手架配置)中直接可以在package.json文件中配置

'proxy':'http://localhost:3000'

配置了此代理后,在发送请求的时候,将请求地址替换为配置的地址,不包含端口后面的路径。这时候发送请求时,将会由代理地址转发给服务器地址。

使用

axios.get('/1').then(res => {
  console.log('成功', res);
}).catch(error => {
  console.log('失败', error);
})

Vue项目((脚手架vue-cli项目)根目录创建vue.config.js文件配置

module.exports = {
  pages: {
    index: {
      entry: 'src/main.js'
    }
  },
  devServer: {
    proxy: 'http://localhost:3000'
  }
}

使用和react使用相同。

2.多类代理,这种配置可以配置多个代理,也是全局生效。

React项目(脚手架配置)

2.1 首先在src目录下,创建文件setupProxy.js,这是 webpack 指定的文件名。

2.2 文件中配置代码参数,分1.x版本和2.x版本,两个版本略有差别

1.x版本

//引入node的中间件
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
 app.use(
   proxy('/api', { 
     target: 'http://localhost:3000', //所网络请求的地址
     changeOrigin: true, //是否修改服务器接受到的请求头中的host
     pathRewrite: {'^/api': ''} //重写路径
   }),
   proxy('/oss', { 
     target: 'http://localhost:4000', 
     changeOrigin: true, 
     pathRewrite: {'^/oss': ''} 
   }),
 )
}

2.x版本

//引入方式改变
const createProxyMiddleware = require("http-proxy-middleware")

module.exports = function (app) {
    app.use(
        '/api', 
        createProxyMiddleware({ //配置方式改变
           target: 'http://localhost:3000',
           changeOrigin: true,
           pathRewrite: {'^/api': ''}
        })
    ),
    app.use(
        '/oss', 
        createProxyMiddleware({
           target: 'http://localhost:4000',
           changeOrigin: true,
           pathRewrite: {'^/oss': ''}
        })
    )
}

参数解:

  • http-proxy-middleware:node 的中间件,1.x 和 2.x 使用的方式有些改变
  • app.use():配置多个代理项
  • '/api'|'/oss':配置标识的前缀
  • target:所需要转发的网络请求地址,协议+域名(ip)+端口
  • changeOrigin:是否转修改给服务器请求头的host信息,false为原始host,true会修改为转发的host,默认为false
  • pathRewrite:重写路径,重写所需的路径。

使用

axios.get('/api').then(res => {
  console.log('成功', res);
}).catch(error => {
  console.log('失败', error);
})

axios.get('/oss/img1/').then(res => {
  console.log('成功', res);
}).catch(error => {
  console.log('失败', error);
})

Vue项目(脚手架vue-cli项目)根目录创建vue.config.js文件配置,但配置的内容有所变化。

module.exports = {
  pages: {
    index: {
      entry: 'src/main.js'
    }
  },
  devServer: {
    '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {'^/api': ''}
   },
    '/oss': {
    target: 'http://localhost:4000',
    changeOrigin: true,
    pathRewrite: {'^/oss': ''}
   },
}

参数和react中配置的一样,注意的一点是vue中changeOrigin默认是true

使用和react使用相同。

两种方式的比较:
  • 配置一:优点:配置简单;缺点:只能配置一个代理,并且如果本项目public目录下有请求的路径资源时,则不再继续转发代理请求,而是直接获取本地的该路径资源(优先匹配本地资源)

  • 配置二:优点:可以灵活配置多个代理,配置的资源都会转发代理,不会走本地;缺点:配置相对繁琐,在请求的时要加上相应的前缀。