两种方法选其一即可

一、后端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');
        
    })
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部