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端的路由下配置相关的路由之类的?
关于 LearnKu
首先看看浏览器控制台请求的地址是什么。 这个功能是由
vite提供的 所以只有在vite服务下的本地请求才会被代理转发。比如http://localhost:5173/api/index,按照你的配置会转发到https://dog.ceo/api/breed/pembroke/images/random/api/index。你使用 Laravel 开发的话,页面打开的地址应该是 php 提供的服务,比如
http://localhost这样你在页面进行请求是,走的是 Laravel 服务的这一套,根本到不了vite, 所以你看到的是index.blade.php的内容。所以你可以试试
axios.defaults.baseURL = 'http://localhost:5173/api';。好久没搞 Laravel 不记得内部和vite是如何结合的,以上内容可能会有误。。。