使用vue+axios+vite实现跨域请求
1、route.js
import { createRouter, createWebHistory} from 'vue-router'
const routerHistory = createWebHistory() const router = createRouter({ history: routerHistory, routes }) export default router;
2、main.js
import { createApp,h } from 'vue' import router from './route/route' import axios from "axios"; import VueAxios from 'vue-axios'
axios.defaults.headers.post['Content-Type']='application/json' const app = createApp(App) app.config.globalProperties.$axios = axios axios.defaults.withCredentials = true axios.defaults.baseURL = '/api'
app.use(VueAxios, axios) app.use(router).use(ElementPlus).mount('#app')
3、vite.config.js
module.exports = { proxy: { '/api': { target: 'http://', //你要跨域访问的网址 changeOrigin: true, // 允许跨域 rewrite: (path) => path.replace(/^\/api/, '') // 重写路径把路径变成空字符 } } }
4、使用
this.$axios .post('/zentao/search-buildQuery', testData, { params: { zentaosid: this.sessionID, } }) .then(res => { this.getOrderBugSearchList() }).catch(err => { console.log(err) });