草庐IT

Vue中如何解决跨域问题

无信_不立 2023-04-21 原文

跨域

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

 

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

 

 

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

 

 

 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>

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

 

 

原理:

 

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

 

在启动脚手架的时候会启动一个内置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)

 })

有关Vue中如何解决跨域问题的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  5. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  6. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  7. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  8. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

随机推荐