前言
在写项目中,你可能会遇到开发环境下的跨域问题。为了解决这个问题,你可以在Vite的配置文件中使用代理(proxy)功能来解决前后端跨域问题。
一、什么是跨域?
跨域(Cross-Origin)是指在网络环境中,一个网页的文档或脚本试图去访问另一个网站的资源时,由于浏览器的同源策略(Same-Origin Policy)限制,请求会被浏览器禁止或限制的行为。以下是对跨域的详细解析:
- 同源策略:
- 同源策略是浏览器的一种安全机制,用于限制不同源的网页如何相互访问和交互。
- 同源指的是两个页面具有相同的协议(protocol)、域名(host)和端口号(port)。
- 跨域问题的产生:
- 当请求URL的协议、域名、端口三者中的任意一个与当前页面URL不同时,即发生跨域。
- 跨域问题主要源于浏览器的同源策略限制,以确保用户信息安全和防止恶意网站访问
像这种报错就是出现了跨域问题。
二、解决跨域
使用Proxy代理解决跨域。
代码如下(示例):
vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
'/api': {
target: 'http://localhost:8080', // 后端服务器地址
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
});
前端代码:
<template>
<div>
<h1>数据:{{ data }}</h1>
</div>
</template>
<script setup>
import axios from 'axios';
import {onMounted} from 'vue
onMounted(() => {
axios.get('/api/test8')
.then(response => {
this.data = response.data;
})
.catch(error => {
console.error('请求失败:', error);
});
}
})
</script>
后端node代码服务器搭建
const express = require('express');
const app = express();
const port = 8080;
// 示例路由
app.get('/data', (req, res) => {
res.json({ message: 'Hello from Express server!' });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
成功解决跨域。