Vue中如何解决跨域问题

本文详细介绍了前端开发中遇到的跨域问题及其原因,包括浏览器的同源策略。通过示例展示了如何使用Vue结合Express搭建服务器进行跨域演示,并提供了解决Vue项目跨域的两种方法:配置代理服务器和在Express中使用cors模块处理跨域。这些方法适用于开发阶段,线上环境通常由后端处理跨域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

跨域报错是前端开发中非常经典的一个错误,报错如下

 Access to XMLHttpRequest at '......' from origin 

 '......' has been blocked by CORS policy: 

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

跨域错误源自于浏览器的同源策略,想要解决跨域首先要知道什么是同源策略?

 

一、同源策略?

同源策略:著名的安全策略,URL有三个基本组成部分:协议+域名或ip+端口,三个必须完全相同称之为同源,不同源的称之为跨域

 

URL 与 URL 对比:

http://localhost:3000/

https://localhost:3000/ 不同源:协议不同

http://localhost:3000/

http://127.0.0.1:3000/ 不同源:域名或ip不同

http://localhost:3000/

http://localhost:3001/ 不同源:端口不同

http://localhost:3000/

http://localhost:3000/ 同源

http://127.0.0.1:3000/

http://127.0.0.1:3000/ 同源

注意:同源策略不是服务器行为,而是浏览器的行为,服务器会正常响应请求,但是如果不同源会被浏览器拦截

 

搭建express服务器——演示

搭建一个express服务器用来演示跨域报错

安装express

 npm i express

 

在app.js文件中

 let express = require('express')

 let app = express()

 ​

 app.listen(3000, () => {

     console.log('服务器已启动..端口3000.')

 })

 ​

 app.use(express.static('./views'))

 ​

 app.get('/getTest', (req, res) => {

     console.log(req.query)

     res.send(req.query)

 })

 

在views/index.html文件中

 

 <!DOCTYPE html>

 <html>

 ​

 <head>

     <meta charset="UTF-8">

     <title>Document</title>

     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

     <script>

         function getIpTest() {

             axios({

                 method: "get",

                 url: "http://127.0.0.1:3000/getTest",

                 params: { uid: 123 },

             }).then((res) => {

                 console.log(res.data);

             });

         }

         function getDnameTest() {

             axios({

                 method: "get",

                 url: "http://localhost:3000/getTest",

                 params: { uid: 123 },

             }).then((res) => {

                 console.log(res.data);

             });

         }

     </script>

 </head>

 ​

 <body>

     <button οnclick="getIpTest()">getIpTest</button>

     <button οnclick="getDnameTest()">getDnameTest</button>

 </body>

 ​

 </html>

打开浏览器访问http://127.0.0.1:3000/

 

(1)调用getIpTest发送请求不会报错,因为浏览器地址栏访问的服务器是http://127.0.0.1:3000/** ,而方法内发送请求的URL也是http://127.0.0.1:3000/** ,视为同源

 

(2)调用getDnameTest发送请求报错,因为浏览器地址栏访问的服务器是http://127.0.0.1:3000/** ,而方法内发送请求的URL也是http://localhost:3000/** ,视为跨域

6d65a61429a74ae5bbbf00db1690749b.png

 

 Access to XMLHttpRequest at 'http://localhost:3000/......' from origin 

 'http://127.0.0.1:3000' has been blocked by CORS policy: 

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

打开浏览器访问http://localhost:3000/

 

(3)调用getDnameTest发送请求不会报错,因为浏览器地址栏访问的服务器是http://localhost:3000/ ,而方法内发送请求的URL也是http://localhost:3000/ ,视为同源

 

(4)调用getIpTest发送请求报错,因为浏览器地址栏访问的服务器是http://localhost:3000/ ,而方法内发送请求的URL也是**http://127.0.0.1:3000/** ,视为跨域

4a89278b647d4132a471101a18f8350b.png

 

 

 Access to XMLHttpRequest at 'http://127.0.0.1:3000/......' from origin 

 'http://localhost:3000' has been blocked by CORS policy: 

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

二、vue如何处理跨域问题?

(1)创建vue项目,安装axios模块

 

 vue create app //创建vue

 npm install axios vue-axios //安装axios

 

在main.js中

 

 import axios from 'axios'

 import VueAxios from 'vue-axios'

 Vue.use(VueAxios, axios)

 

在views/About.vue中

 

 <template>

   <div class="about">

     <button @click="getTest()">getTest</button>

   </div>

 </template>

 ​

 <script>

 export default {

   methods: {

     getTest() {

       this.axios({

         method: "get",

         url: "http://127.0.0.1:3000/getTest",

         params: { uid: 123 },

       }).then((res) => {

         console.log(res.data);

       });

     },

   },

 };

 </script>

 

脚手架项目端口是8080而请求的express服务器端口是3000,不满足同源策略,发送请求报跨域错误

811a362f883346ccb87fbe857714600b.png

 

 

 Access to XMLHttpRequest at 'http://127.0.0.1:3000/......' from origin 

 'http://127.0.0.1:8080' has been blocked by CORS policy: 

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

(2)解决办法

 1.配置代理服务器

在vue.config.js文件中

(修改后需要重启脚手架项目)

 const { defineConfig } = require('@vue/cli-service')

 module.exports = defineConfig({

   transpileDependencies: true,

   devServer: {

     //配置http-proxy代理方式跨域

     proxy: {

       // 自定义请求的开头,使用代理方式处理/demo开头的请求,/xxx可以自定义

       "/demo": {

         // 往哪个服务器发请求

         target: "http://127.0.0.1:3000",

         pathRewrite: {

           // ^代表字符串开头,实际发送请求时,会把请求开头的/demo删除

           // 因为/demo并不是请求的一部分,只是个代理的标识

           "^/demo": "",

         },

       },

       // 如果有其他网址也需要跨域则继续配置

       // "/其他的...": {

       // target: "其他的请求地址",

       // pathRewrite: {

       // "^/其他的...": "",

       // },

       // },

     },

   },

 })

在views/About.vue文件中

 

 <template>

   <div class="about">

     <button @click="getTest()">getTest</button>

   </div>

 </template>

 ​

 <script>

 export default {

   methods: {

     getTest() {

       this.axios({

         method: "get",

         // 在原来的url上去掉http://127.0.0.1:3000换成/demo

         url: "/demo/getTest",

         params: { uid: 123 },

       }).then((res) => {

         console.log(res.data);

       });

     },

   },

 };

 </script>

22099be2380c4a2985c8141920cd4867.png

 

 

原理:

跨域是浏览器的安全策略,服务器和服务器之间发送请求没有跨域

在启动脚手架的时候会启动一个内置web服务器

请求的时候浏览器实际并没有直接和需要请求的服务器通信,而是通过内置的web服务器在中转

 

注意:

项目上线需要把打包后的文件放在服务器上运行,而不是启动脚手架运行,也就没有内置web服务器做代理,所以此方式只适用于开发测试阶段

上线时一般后端解决跨域问题

需要使用nginx代理或者服务器配置cors(每种语言有自己不同的配置方式)

 

2.express处理跨域

express中处理跨域需要使用cors模块

 

 npm i cors

在app.js文件中

 

 let express = require('express')

 // 引入cors模块

 var cors = require("cors");

 let app = express()

 ​

 app.listen(3000, () => {

     console.log('服务器已启动...')

 })

 ​

 // 配置跨域

 app.use(cors({

     // 允许跨域的服务器地址,可以写多个

     origin: ['http://localhost:8080', 'http://127.0.0.1:8080'],

     // 使用cookie时需要设置为true

     credentials: true

 }));

 ​

 app.use(express.static('./views'))

 ​

 app.get('/getTest', (req, res) => {

     console.log(req.query)

     res.send(req.query)

 })

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值