在vue项目中,前端与后台进行数据请求或者提交时,如果后台没有设置跨域,那么前端本地调试代码的时候就会报错


使用http-proxy-middleware 代理解决(注意:项目使用vue-cli脚手架搭建)

例如请求的接口为:'http://172.16.2.212:10000/api/micro/productStore/getSubCategoryListAndProd'

  1. 从项目的根目录下打开config/index.js文件,在proxyTable中添加如下代码:
        proxyTable: {
    		  '/pcApi': {
    		    target: 'http://172.16.2.212:10000/api/micro',
    		    changeOrigin: true,
            pathRewrite: {
              '^/pcApi': ''
            }
          }
    		},
  2. 使用axios请求数据时直接使用'/pcApi':
        getHotSell () {
            this.$get({
              url: '/pcApi/productStore/getSubCategoryListAndProd/gouwuchetuijian/CN-3101',
              success:function (res) {
                console.log(res)
              }
            })
          }

     

  3. 通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下: 

    let serverUrl = '/api/'  //本地调试时 
    // let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 
    export default { 
      dataUrl: serverUrl + 'bj11x5.json' 
    }

     

     

 

Logo

前往低代码交流专区

更多推荐