• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

37.Vue3网络请求跨域解决方案

武飞扬头像
想成为数据分析师的开发工程师
帮助1

什么是同源,什么是跨域,跨域解决


概述

同源?

  JS采用的是同源。同源策略是浏览器的一项安全策略,浏览器只允许js代码请求和当前所在的服务器域名,端口,协议相同的数据接口上的数据。

什么是跨域?

浏览器不可以执行其他网站的脚本。是由浏览器的同源所造成的。也就是说,例如一个网站http://iwenwiki.com,当协议(http://),域名(iwenwiki.com),端口(可以省略:8080)不同时,就会产生跨域问题。

测试跨域:

  1.  
    <template>
  2.  
    <div class="hello">
  3.  
    <h1>跨域解决方案之proxy</h1>
  4.  
    </div>
  5.  
    </template>
  6.  
     
  7.  
    <script>
  8.  
    import axios from "axios"
  9.  
     
  10.  
    export default {
  11.  
    name: 'HelloWorld',
  12.  
    mounted(){
  13.  
    axios.get("http://iwenwiki.com/api/FingerUnion/list.php")
  14.  
    .then(res=>{
  15.  
    console.log(res.data);
  16.  
    })
  17.  
    }
  18.  
    }
  19.  
    </script>
学新通

 

学新通

解决方案:前台proxy

组件中

  1.  
    <template>
  2.  
    <div class="hello">
  3.  
    <h1>跨域解决方案之proxy</h1>
  4.  
    </div>
  5.  
    </template>
  6.  
     
  7.  
    <script>
  8.  
    import axios from "axios"
  9.  
     
  10.  
    export default {
  11.  
    name: 'HelloWorld',
  12.  
    mounted(){
  13.  
    axios.get("/api/FingerUnion/list.php")
  14.  
    .then(res=>{
  15.  
    console.log(res.data);
  16.  
    })
  17.  
    }
  18.  
    }
  19.  
    </script>
学新通

在vue.config.js中

  1.  
    const { defineConfig } = require('@vue/cli-service')
  2.  
    module.exports = defineConfig({
  3.  
    transpileDependencies: true,
  4.  
    // 前台解决方案:proxy
  5.  
    devServer:{
  6.  
    proxy:{
  7.  
    '/api':{
  8.  
    target:'http://iwenwiki.com/',
  9.  
    changeOrigin:true
  10.  
    }
  11.  
    }
  12.  
    }
  13.  
    })

总结

前台解决:proxy

后台解决:cors

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhiecfif
系列文章
更多 icon
同类精品
更多 icon
继续加载