溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue項(xiàng)目中怎么解決跨域問(wèn)題

發(fā)布時(shí)間:2022-06-10 09:30:41 來(lái)源:億速云 閱讀:429 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Vue項(xiàng)目中怎么解決跨域問(wèn)題”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Vue項(xiàng)目中怎么解決跨域問(wèn)題”吧!

跨域

跨域報(bào)錯(cuò)是前端開發(fā)中非常經(jīng)典的一個(gè)錯(cuò)誤,報(bào)錯(cuò)如下

 Access to XMLHttpRequest at '......' from origin 
 '......' has been blocked by CORS policy: 
 No 'Access-Control-Allow-Origin' header is present on the requested resource.

跨域錯(cuò)誤源自于瀏覽器的同源策略,想要解決跨域首先要知道什么是同源策略

同源策略

同源策略:著名的安全策略,URL有三個(gè)基本組成部分:協(xié)議+域名或ip+端口,三個(gè)必須完全相同稱之為同源,不同源的稱之為跨域

URLURL對(duì)比
http://localhost:3000/https://localhost:3000/不同源:協(xié)議不同
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/同源

注意:同源策略不是服務(wù)器行為,而是瀏覽器的行為,服務(wù)器會(huì)正常響應(yīng)請(qǐng)求,但是如果不同源會(huì)被瀏覽器攔截

express服務(wù)器

搭建一個(gè)express服務(wù)器用來(lái)演示跨域報(bào)錯(cuò)

安裝express

 npm i express

app.js

 let express = require('express')
 let app = express()
 
 app.listen(3000, () => {
     console.log('服務(wù)器已啟動(dòng)...')
 })
 
 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>

打開瀏覽器訪問(wèn)http://127.0.0.1:3000/

調(diào)用getIpTest發(fā)送請(qǐng)求不會(huì)報(bào)錯(cuò),因?yàn)闉g覽器地址欄訪問(wèn)的服務(wù)器是http://127.0.0.1:3000/ ,而方法內(nèi)發(fā)送請(qǐng)求的URL也是http://127.0.0.1:3000/ ,視為同源

調(diào)用getDnameTest發(fā)送請(qǐng)求報(bào)錯(cuò),因?yàn)闉g覽器地址欄訪問(wèn)的服務(wù)器是http://127.0.0.1:3000/ ,而方法內(nèi)發(fā)送請(qǐng)求的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.

打開瀏覽器訪問(wèn)http://localhost:3000/

調(diào)用getDnameTest發(fā)送請(qǐng)求不會(huì)報(bào)錯(cuò),因?yàn)闉g覽器地址欄訪問(wèn)的服務(wù)器是http://localhost:3000/ ,而方法內(nèi)發(fā)送請(qǐng)求的URL也是http://localhost:3000/ ,視為同源

調(diào)用getIpTest發(fā)送請(qǐng)求報(bào)錯(cuò),因?yàn)闉g覽器地址欄訪問(wèn)的服務(wù)器是http://localhost:3000/ ,而方法內(nèi)發(fā)送請(qǐng)求的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處理跨域

創(chuàng)建vue項(xiàng)目,安裝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>

腳手架項(xiàng)目端口是8080而請(qǐng)求的express服務(wù)器端口是3000,不滿足同源策略,發(fā)送請(qǐng)求報(bào)跨域錯(cuò)誤

 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.

解決辦法: 配置代理服務(wù)器

vue.config.js:修改后需要重啟腳手架項(xiàng)目

 const { defineConfig } = require('@vue/cli-service')
 module.exports = defineConfig({
   transpileDependencies: true,
   devServer: {
     //配置http-proxy代理方式跨域
     proxy: {
       // 自定義請(qǐng)求的開頭,使用代理方式處理/demo開頭的請(qǐng)求,/xxx可以自定義
       "/demo": {
         // 往哪個(gè)服務(wù)器發(fā)請(qǐng)求
         target: "http://127.0.0.1:3000",
         pathRewrite: {
           // ^代表字符串開頭,實(shí)際發(fā)送請(qǐng)求時(shí),會(huì)把請(qǐng)求開頭的/demo刪除
           // 因?yàn)?demo并不是請(qǐng)求的一部分,只是個(gè)代理的標(biāo)識(shí)
           "^/demo": "",
         },
       },
       // 如果有其他網(wǎng)址也需要跨域則繼續(xù)配置
       // "/其他的...": {
       //   target: "其他的請(qǐng)求地址",
       //   pathRewrite: {
       //     "^/其他的...": "",
       //   },
       // },
     },
   },
 })

views/About.js

 <template>
   <div class="about">
     <button @click="getTest()">getTest</button>
   </div>
 </template>
 
 <script>
 export default {
   methods: {
     getTest() {
       this.axios({
         method: "get",
         // 在原來(lái)的url上去掉http://127.0.0.1:3000換成/demo
         url: "/demo/getTest",
         params: { uid: 123 },
       }).then((res) => {
         console.log(res.data);
       });
     },
   },
 };
 </script>

原理:

跨域是瀏覽器的安全策略,服務(wù)器和服務(wù)器之間發(fā)送請(qǐng)求沒有跨域

在啟動(dòng)腳手架的時(shí)候會(huì)啟動(dòng)一個(gè)內(nèi)置node服務(wù)器

請(qǐng)求的時(shí)候?yàn)g覽器實(shí)際并沒有直接和需要請(qǐng)求的服務(wù)器通信,而是通過(guò)內(nèi)置的node服務(wù)器在中轉(zhuǎn)

注意:

項(xiàng)目上線需要把打包后的文件放在服務(wù)器上運(yùn)行,而不是啟動(dòng)腳手架運(yùn)行,也就沒有內(nèi)置node服務(wù)器做代理,所以此方式只適用于開發(fā)測(cè)試階段

上線時(shí)需要使用nginx代理或者服務(wù)器配置cors(每種語(yǔ)言有自己不同的配置方式)

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('服務(wù)器已啟動(dòng)...')
 })
 
 // 配置跨域
 app.use(cors({
     // 允許跨域的服務(wù)器地址,可以寫多個(gè)
     origin: ['http://localhost:3000', 'http://127.0.0.1:3000'],
     // 使用cookie時(shí)需要設(shè)置為true
     credentials: true
 }));
 
 app.use(express.static('./views'))
 
 app.get('/getTest', (req, res) => {
     console.log(req.query)
     res.send(req.query)
 })

到此,相信大家對(duì)“Vue項(xiàng)目中怎么解決跨域問(wèn)題”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI