温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue项目中怎么解决跨域问题

发布时间:2022-06-10 09:30:41 来源:亿速云 阅读:484 作者:iii 栏目:开发技术

本篇内容主要讲解“Vue项目中怎么解决跨域问题”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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+端口,三个必须完全相同称之为同源,不同源的称之为跨域

URLURL对比
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)  })

到此,相信大家对“Vue项目中怎么解决跨域问题”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI