解决vue3跨域问题
1、使用jsonp,注意只能解决发送get请求时跨域问题
安装
npm install vue-jsonp -S
在main中添加引入:
vue2写法
import { VueJsonp } from 'vue-jsonp'
Vue.use(VueJsonp)
vue3写法:
import { jsonp } from 'vue-jsonp';
app.config.globalProperties.$jsonp= jsonp
使用:
const { proxy } = getCurrentInstance();
export const translate = async ()=> {
if(!q) return
let body = {
q: "测试",
source: "auto",
target: "en",
format: "text",
alternatives: 3,
api_key: ""
}
proxy.$jsonp(url, body)
.then(response => {
console.log(response.data)
}).catch(error => {
console.error(error)
})
}
在文件中引入的方法:
import { jsonp } from 'vue-jsonp';
直接使用:
export const translate = async ()=> {
if(!q) return
let body = {
q: "测试",
source: "auto",
target: "en",
format: "text",
alternatives: 3,
api_key: ""
}
jsonp(url, body)
.then(response => {
console.log(response.data)
}).catch(error => {
console.error(error)
})
}
2、使用axios方法,可以执行post请求解决跨域
安装
npm install axios
同样在vue3中main配置:
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')
使用:
const { proxy } = getCurrentInstance();
export const translate = async ()=> {
if(!q) return
let body = {
q: "测试",
source: "auto",
target: "en",
format: "text",
alternatives: 3,
api_key: ""
}
proxy.$axios(url, body)
.then(response => {
console.log(response.data)
}).catch(error => {
console.error(error)
})
}