关于vue.js:Vue中如何解决跨域问题

6次阅读

共计 4262 个字符,预计需要花费 11 分钟才能阅读完成。

跨域报错是前端开发中十分经典的一个谬误,报错如下

 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 onclick="getIpTest()">getIpTest</button>
     <button onclick="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/,视为跨域

 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/,视为跨域

 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.js

 <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,不满足同源策略,发送申请报跨域谬误

 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.js

 <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>

原理:

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

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

申请的时候浏览器理论并没有间接和须要申请的服务器通信,而是通过内置的 node 服务器在直达

留神:

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

上线时须要应用 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:3000', 'http://127.0.0.1:3000'],
     // 应用 cookie 时须要设置为 true
     credentials: true
 }));
 
 app.use(express.static('./views'))
 
 app.get('/getTest', (req, res) => {console.log(req.query)
     res.send(req.query)
 })
正文完
 0