vue解决跨域
vue-cli2
main.js
import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = '/api' Vue.config.productionTip = false
.vue
var This = this var url = '/group1/M00/00/21/MejEvGOX_zOAL2kiAAAAUhB5Iqg138.txt?token=895acb60323e38e6d85b5c9a82466b61&ts=1670934451' axios.get(url, {responseType: 'blob'}) .then((response) => { console.log('跨域,设置返回类型', response) This.handleExport(response.data) })
config/index.js
proxyTable: { '/api': { target: 'https://tyzfbj.com', // http://172.16.33.27:5566/getHelp secure: false, changeOrigin: true, pathRewrite: { '^/api': ''//表示需要rewrite重写路径 } } },
vue-cli3解决跨域(正式环境和测试环境)
1.修改vue.config.js
根目录创建 vue.config.js
devServer: { open: true, //是否自动弹出浏览器页面 host: "localhost", port: 8080, // https: false, hotOnly: false, proxy: { '/api': { target: process.env.VUE_APP_URL, changeOrigin: true, // 虚拟的站点需要更管origin pathRewrite: { '^/api': '/' //本地 // '^/api': '/api' } } }, },
2.env设置process.env.VUE_APP_URL
根目录创建.env文件
3.main.js
axios.defaults.baseURL = process.env.NODE_ENV === "deveplopment"?"/api":process.env.VUE_APP_URL
Vue.prototype.$http = axios;
4.设置请求url
bdbaseUrl = process.env.NODE_EN == "development"?"/api":process.env.VUE_APP_URL
5.接口调用
.vue
await conversate(this.ConverBotsInput) .then((res) => { console.log("调用接口的结果", res); if (res.data.code == 200) { this.ConverBotsOutput = res.data.data; } else { this.$message.error("自然语言闲聊失败"); } }) .catch((error) => { console.log("获取失败", error); this.$message.error("自然语言闲聊失败"); });
index.js
export const conversate = data => { //百度 文心一言 return instance3({ url: '/chat/inquire/create?inquireMessage='+data, method: 'post', }) }
request.js
bdbaseUrl = process.env.NODE_EN == "development"?"/api":process.env.VUE_APP_URL const instance3 = axios.create({ baseURL: bdbaseUrl,//bdbaseUrl timeout: 1500000 }) instance3.interceptors.request.use(config => { console.log('config', config) console.log('axios.defaults.baseURL', axios.defaults.baseURL) // config.headers['Content-Type'] ='application/x-www-form-urlencoded;charset=UTF-8' config.method === 'post' ? config.params = config.data: config.params = { ...config.params } if (config.url != '/api/auth/login' && config.url != '/api/auth/RefreshToken') { let currentTime = new Date().getTime() //token过期时间 let expirationTime = new Date(JSON.parse(localStorage.expiration)).getTime() if (currentTime < expirationTime) { //token未过期 config.headers.Authorization = 'Bearer ' + JSON.parse(localStorage.token); //将token设置成请求头 } else { //token已过期 console.log("登录已超时,请重新登录"); } } return config }, error => { // 请求错误处理 // app.$vux.toast.show({ // type: 'warn', // text: error // }); console.log('请求错误处理') Promise.reject(error) })