跨域请求网络配置

250 阅读4分钟

CROS解决跨域请求

image.png

image.png

使用CROS解决跨域请求,就需要在请求数据的后端服务器配置允许跨域的网址,允许的网址就可以跨域请求文件资源。Egg框架提供了 egg-cors 插件来实现cors跨域请求,需要先下载然后在插件配置文件中配置插件的功能。

以下图片就是AJAV请求http://192.168.0.109:7001/hyomin的数据

image.png

配置了请求数据的后端服务器允许该网址http://192.168.0.109:8081/进行跨域请求

image.png

<template>
  <div id="app">
    <nav1></nav1>
    <p>{{info.name}}</p>
    <p>{{info.singer}}</p>
  </div>
</template>

<script>
  import nav1 from '@/components/Nav1.vue';
  import axios from 'axios';//会在nodule_modules中找到的axios文件夹中引入一份js文件
  export default{
    data() {
      return {
        info:""
      }
    },
    components:{
      nav1
    },
    async mounted() {
      let res=await axios("http://192.168.0.109:7001/hyomin");
      console.log(res);
      this.info=res.data;
    },
  }
</script>

<style lang="scss">

</style>
//egg后端返回数据的函数
async hyomin(){
    this.ctx.body={name:"启示录",singer:"Gloria"};
  }

info:""提前在数据源中将一个未来网络请求得到的数据先设为空对象,就避免在页面首次渲染时,会因为undefined使用点语法报错而导致程序停止运行。设置为一个空对象,对象用点语法取没有的属性值就返回undefined,页面不会渲染undefined,而当网络请求成功获取到数据,数据源中的数据更新了再次刷新页面就将请求到的数据渲染了在页面上。

image.png

Proxy配置代理服务器解决跨域请求

这是项目开发中常用的一种解决跨域请求因为服务器之间不受浏览器的同源策略影响不存在跨域请求,同时也方便上线时将代码进行迁移。因为在项目中做网络请求时只需要写相对网络路径做网络请求不需要将网络请求的网址写成绝对网址,最后将baseURL基础路径修改即可,就不用去改变项目中做网络请求的代码。

比如:axios("/hyomin"),此时真正请求的网址是 http://192.168.0.109:8081/tara/hyomin,就可以配置8081所在的服务器为代理服务器帮我们去请求7001所在的服务器上的该网址http://192.168.0.109:7001/hyomin的数据。

想要达到上诉效果,需要进行公共网址配置和8081服务器的代理

1.在组件的原型链上也就是Vue实例的原型对象上配置axios工具和配置公共网址,因为组件实例对象都可以访问到Vue原型上的属性和方法。

main.js文件中:
import axios from "axios";
Vue.prototype.$axios=axios;
Vue.prototype.$axios.defaults.baseURL="http://ip:8081/tara";

2.配置8081服务的代理,配置/tara开头的网址做代理,配置好之后项目中以/tara开头的网址8081服务器就会代理帮我们请求数据,不是这个开头的网址就不会帮我们代理。代理配置中可以配置多个代理接口,配置过的接口然后项目中以这些接口开头的网址都会帮我们代理。

vue.config.js文件:
lintOnSave: false, //关闭eslint的严格模式检测,
 devServer: {
 	port: 8081, //默认vue脚手架配置就8081
 	//代理配置,这里只是配置,不用写代理服务器的代码(配置好了它帮我们实现)
        //配置方法1
 	// proxy: {
 	// 	'/api': 'http://localhost:7001',
 	// },
        //配置方法2,也是常用的方法
 	proxy: {
 		'/xxx': {
 			target: 'http://192.168.101.109:7001',
 			secure: true, //如果代理的target是https接口,需要配置它 
 			pathRewrite: {
 				'^/xxx': '/'
 			}, 
 			//请求时重写pathname:也就是配置的公共网址
 			//项目组件中请求的是http://192.168.101.109:8081/xxx/ajax1
 			//8081服务器就会帮我们代理请求 http://192.168.101.109:7001/ajax1
 			
 			//项目组件中请求的是http://192.168.101.109:8081/test/ajax1 那么proxy就检测不到 就不会做代理,它只会代理xxx开头的
 		},
 		
 		'/sina': {
 			target: 'http://某个公司的网址',
 			secure: true, //如果代理的target是https接口,需要配置它 
 			pathRewrite: {
 				'^/sina': '/aaa'
 			}, 
 			//请求时重写pathname: 
 			//项目组件中请求的是http://192.168.101.109:8081/sina/ajax1
 			//8081服务器就会帮我们代理请求 http://某个公司的网址/aaa/ajax1	
 						
 			//项目组件中请求的是http://192.168.101.109:8080/test/ajax1 那么proxy就检测不到 就不会做代理
 		},
 	},
 }

3.组件中使用this.$axios("/hyomin")

整个运行的流程: $axios是原型上的那个工具就会基于它的baseURL请求"/hyomin" 因此就会请求baseURL+"/ajax1" ,然后baseURL又是8081服务器中代理配置过的,检测到网址中包含了代理的关键字网址就会去代理请求target网址。

QQ图片20220906232123.png

1.组件的原型链上配置axios工具和配置公共网址

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.prototype.$axios=axios
Vue.prototype.$axios.defaults.baseURL='http://192.168.0.109:8081/tara'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

2.服务器代理配置

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    port:8081,
    proxy:{
      '/tara':{
        target: 'http://192.168.0.109:7001',
        secure: true, //如果代理的target是https接口,需要配置它
        pathRewrite:{
          '^/tara':'/'
        }
      }
    }
  }
})

3.组件中使用axios做网络请求

<template>
  <div id="app">
    <nav1></nav1>
    <button @click="ajax">点击发起网络请求</button>
    <div class="msgbox" v-for="(el,index) in msg" :key="index">
      <h1>{{el.title}}</h1>
      <span v-for="(el1,index1) in el.music" :key="index1">{{el1}}-----</span>
    </div>
  </div>
</template>

<script>
  import nav1 from '@/components/Nav1.vue';

  export default{
    data() {
      return {
        msg:""
      }
    },
    methods: {
      async ajax(){
        let data=await this.$axios("/youngmini");
        console.log(data,22222);
        this.msg=data.data;
      }
    },
    components:{
      nav1
    }
  }
</script>

<style lang="scss">

</style>

image.png

image.png