vite通过proxy解决跨域问题

vite通过proxy解决跨域问题
同源策略保护,跨域请求

一、 在 vite.config.js 开启跨域

在这里插入图片描述

import {
    
     defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    
    
    plugins: [vue()],

    server: {
    
    
        proxy: {
    
    
            '/path': {
    
    
                target: 'https://elf-deco.maibaapp.com',//替换的服务端地址
                changeOrigin: true,//开启代理,允许跨域
                rewrite: path => path.replace(/^\/path/, '')//设置重写的路径
            }
        }
    }
})

二、引入axios

安装

npm install axios

三、使用

例子请求
https://elf-deco.maibaapp.com/content/wxapp/loversProfile/json/lovers-1.json

<script setup>
import axios from 'axios'
axios.get('/path/content/wxapp/loversProfile/json/lovers-1.json').then((res)=>{
    
    
  console.log(res.data)
})
</script>

内容

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Linlietao0587/article/details/128392187