这篇文章主要介绍了Vue3跨域问题如何解决的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Vue3跨域问题如何解决文章都会有所收获,下面我们一起来看看吧。
vue.config.js
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, devServer:{ proxy:{ '/api':{ target: 'http://xx.xx.xxx.xx', changeOrigin:true, pathRewrite: { '^/api': '' } } } } })
server: { // 跨域的写法 proxy: { '/api': { target: 'http://nvzu.xxx.cn/', // 实际请求地址 changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), }, }, }, // 不跨域的写法 /* server: { host: '192.168.1.195' // 0.0.0.0 }, */
"use strict"; import axios from "axios"; // Full config: https://github.com/axios/axios#request-config axios.defaults.baseURL = '/api' || ''; // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; let config = { // 这里的api就是获取configJS中的地址 baseURL: '/api' // timeout: 60 * 1000, // Timeout // withCredentials: true, // Check cross-site Access-Control }; const _axios = axios.create(config); _axios.interceptors.request.use( function(config) { // Do something before request is sent return config; }, function(error) { // Do something with request error return Promise.reject(error); } ); // Add a response interceptor _axios.interceptors.response.use( function(response) { // Do something with response data return response; }, function(error) { // Do something with response error return Promise.reject(error); } ); export default{ install:function(app){ app.config.globalProperties.axios = _axios; app.config.globalProperties.$translate = (key) =>{ return key } } } /* Plugin.install = function(Vue) { Vue.axios = _axios; window.axios = _axios; Object.defineProperties(Vue.prototype, { axios: { get() { return _axios; } }, $axios: { get() { return _axios; } }, }); }; Vue.use(Plugin) export default Plugin; */
页面使用proxy.axios.get/post进行获取跨域接口
<template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png"> <HelloWorld msg="Welcome to Your Vue.js App"/> </div> </template> <script> import {getCurrentInstance} from 'vue' // 引入Vue3中的getCurrentInstance // @ is an alias to /src import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'HomeView', mounted(){ const {proxy} = getCurrentInstance(); console.log(proxy); // Axios.get proxy.axios.get('/index_category/data').then((e)=>{ console.log(e); }) }, components: { HelloWorld } } </script>
关于“Vue3跨域问题如何解决”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Vue3跨域问题如何解决”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。