两种方法选其一即可
一、后端koa设置中间件
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (ctx.method == 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
})
二、前端
1.vite.config.ts文件配置proxy代理
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import path from 'path'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
},
},
css: {
preprocessorOptions: {
scss: {
additionalData: `
@use "@/style/global.scss" as *;
`,
}
}
},
server:{
proxy:{
"/api":{
target:"http://localhost:3000/",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
2.axios配置文件
import axios from 'axios';
const http=axios.create({
baseURL:'/api',
timeout: 1000
})
export default http;
3.在main.ts文件中引入axios
import { createApp } from 'vue'
import './style.scss'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import {router} from './router/index.ts'
import axios from 'axios'
createApp(App).use(ElementPlus).use(router).mount('#app')
createApp(App).config.globalProperties.$axios=axios
三、使用
import http from '@/plugins/axios'
import {onMounted,ref} from 'vue';
const getData = async () => {
http.get('/products').then(res=>{
console.log('test.res');
})
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 解决跨域问题(vite、axios/koa)
发表评论 取消回复