两种方法选其一即可
一、后端koa设置中间件
TypeScript
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代理
TypeScript
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配置文件
TypeScript
import axios from 'axios';
const http=axios.create({
baseURL:'/api',
timeout: 1000
})
export default http;
3.在main.ts文件中引入axios
TypeScript
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
三、使用
javascript
import http from '@/plugins/axios'
import {onMounted,ref} from 'vue';
const getData = async () => {
http.get('/products').then(res=>{
console.log('test.res');
})
}