Vue项目配置代理 vue.config.js const { defineConfig } = require('@vue/cli-service') module.exports
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/, ""),
},
},
},
// 不跨域的写法
"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
}
}
}
页面使用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跨域解决方案内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Vue3跨域解决方案实例详解
本文链接: https://lsjlt.com/news/178389.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0