vue3 vite 跨域

  • 安装 Vite

npm install vite --save-dev
 

  • 配置 Vite 开发服务器代理

在项目根目录下创建或编辑 vite.config.js 文件,添加代理配置

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

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      // 代理所有 /api 开头的请求到目标服务器
      '/api': {
        target: 'https://example.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
});
 

在这个配置中:

  • target 指定了代理请求的目标服务器。
  • changeOrigin 设置为 true 以便修改请求头中的 Host 字段,使其与目标服务器匹配。
  • rewrite 用于重写请求路径,比如将 /api 前缀移除。

  • 使用代理进行请求

在你的 Vue 组件或其他前端代码中,通过 /api 进行请求,Vite 开发服务器会自动将请求代理到目标服务器。

例如,使用 axios 发起请求:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    fetchData() {
      axios.get('/api/data')
        .then(response => {
          console.log('Data:', response.data);
        })
        .catch(error => {
          console.error('Error:', error);
        });
    }
  }
};
</script>
 

  • 确保后端服务器支持 CORS

即使在开发环境中使用代理解决了跨域问题,在生产环境中部署时,后端服务器仍需支持 CORS。确保服务器的响应头包含适当的 CORS 配置。例如,在 Node.js 和 Express 中可以这样配置:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/data', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值