0


Vue中如何解决跨域问题

跨域

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

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('服务器已启动...')

})

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/

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

调用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/

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

调用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处理跨域

创建vue项目,安装axios模块

vue create app

npm install axios vue-axios

main.js

import axios from 'axios'

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

views/About.vue

<template>
 <button @click="getTest()">getTest</button>
</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.

解决办法: 配置代理服务器

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>
 <button @click="getTest()">getTest</button>
</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服务器在中转

条件结构流程图.png

注意:

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

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

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)

})

标签: 前端

本文转载自: https://blog.csdn.net/ax_ax/article/details/125799658
版权归原作者 无信_不立 所有, 如有侵权,请联系我们删除。

“Vue中如何解决跨域问题”的评论:

还没有评论