前端项目代理配置Proxy

385 阅读1分钟

在前后端分离项目中,一般会涉及到跨域问题,即前端通过ajax或者其它请求向后端请求资源,都会进行跨域(域名不同),更不用说将前后端两个项目部署到不同服务器上,所以便有了代理。

那么如何解决这个问题?在vue项目中,vue-cli有基本的配置,但是我们需要根据我们的项目进行调整。

vue-cli创建的项目,一般是在vue.config.js进行代理配置。下面给出示例

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  lintOnSave: false,
  transpileDependencies: true,
  devServer:{
    proxy:{
      '/dev-api/heigth-on/product-line/list': {
        target: 'http://localhost:8099',
        changeOrigin: true,
        pathRewrite: {
          '^/dev-api': ''
        }
      },
    }
  }
})

这个意思是将以/dev-api/heigth-on/product-line/list开头的请求都代理到http://localhost:8099,即变成http://localhost:8099/dev-api/heigth-on/product-line/list/xxxxx

然后有了pathRewrite,表示路径重写,即将/dev-api变为空,那么最后路径就是http://localhost:8099/heigth-on/product-line/list/xxxxx

一般项目配置

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
};

假设一个前端发送的ajax请求是/api/user,那么最后的浏览器(postman)的实际请求url为:http://localhost:3000/user。

总结而言,前端项目就是client,后端项目就是server,而vue-cli的开发服务器便是他们之间的中间商,便是代理服务器,通过配置这个中间商从而达到代理的作用,如果不了解代理的,可以去查阅正向代理和反向代理内容。