Ruoyi -vue 若依框架 前端跨域访问

总的思路

   创建一个用于第三方平台使用的request拦截器,并定义一个新的path ,最后配置 deserver,其实网上也有很多 对于我这样JAVA开发人员 一下子有点蒙圈,不过摸索一阵子还是解决了。

定义请求第三方平台接口的拦截器

文件名thirdPlatformRequest.js

import axios from 'axios'

const thirdPlatformRequest = axios.create({
  baseURL: '/thirdPlatform-api', 
  timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
thirdPlatformRequest.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=utf-8';

  // config.headers['token'] = user.token;  // 设置请求头
  return config
}, error => {
  return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
thirdPlatformRequest.interceptors.response.use(
  response => {
    let res = response.data;
    // 如果是返回的文件
    if (response.config.responseType === 'blob') {
      return res
    }
    // 兼容服务端返回的字符串数据
    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    return res;
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default thirdPlatformRequest;


定一个新的Path

这里定义的是 ‘/thirdPlatform-api’

deserver的配置

我使用的若依框架前端还是2x版本 所以这段配置时在vue.config.js中,关键代码如下

  devServer: {
    host: '0.0.0.0',
    port: port,
    open: true,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      '/proxy-api': {
         target: `http://localhost:48080/oca/admin-api`,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
          // ['www.baidu.com']:''
        }
      },

      '/thirdPlatform-api': {
        target: `http://bsw.5gkh.org.cn:90/oca/admin-api`,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
          // ['www.baidu.com']:''
        }
      }
    },
    disableHostCheck: true
  

调用

先在 在前端业务接口文件中引入 ,位于src/api下
关键代码如下
import thirdPlatformRequest from “@/utils/thirdPlatformRequest”;

// 获得三维报建申请分页
export function getGtThreeDimensionaleApplyPage(query) {

  // return request({
  //   url: '/gantang/gt-three-dimensionale-apply/page',
  //   method: 'get',
  //   params: query
  // })
  return thirdPlatformRequest({
    url:'/gantang/gt-three-dimensionale-apply/page',
    method:'get',
    params:query
  });
}

结束语

     个人觉得整个关键就是 baseURL: '/thirdPlatform-api',  定义的拦截器中的baseUrl和 deserver中的proxy 要保持 一致 ,
其他的都参考原来的即可, 第一次记录并发表 如有 错误  还望各位看官见谅。
Logo

快速构建 Web 应用程序

更多推荐