laravel10 + vue3 前端axios跨域问题
laravel10集成vue3,前端请求异域资源时,按照网上教程,配置代理请求不生效,会直接请求到laravel的index.blade.php页面,如何才能请求到代理的目标资源?
vite.config.js文件配置代理如下:(具体见server配置项)
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/sass/app.scss',
'resources/js/app.js',
],
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
server: { //cors跨域问题
proxy: {
'/api': {
target: 'https://dog.ceo/api/breed/pembroke/images/random',
changeOrigin: true, //允许跨域
secure: true, //https
rewrite:(path)=>path.replace(/^\/api/, '/api') //路径重写
}
}
},
});
app.js文件配置axios全局挂载
import axios from 'axios';
//全局挂载axios
app.config.globalProperties.$axios = axios;
axios.defaults.baseURL = '/api';
具体函数跨域请求
import { reactive,getCurrentInstance } from 'vue';
export default function () { //暴露数据源
let dogList = reactive([
'https://images.dog.ceo/breeds/pembroke/n02113023_4373.jpg'
])
const { proxy} = getCurrentInstance()
async function getDog() {
proxy.$axios.get('/api').then(res=>{
console.log(res.data);
}).catch(error=>{
console.log(error);
})
}
//向外部提供数据
return { dogList, getDog }
}
调用时,从浏览器console控制台打印的data数据是index.blade.php页面代码,未请求到目标资源。
这种跨域问题怎么解决,还是要在laravel端的路由下配置相关的路由之类的?
推荐文章: