vue--解决请求跨域

2022-09-15 08:26:31

网络请求:
前端最底层:xhr、fetch
二次封装xhr的框架:jquery、axios
这里我使用axios:

引入axios:

npm i axios

跨域错误:违背了同源策略(协议名,主机名,端口号)
在这里插入图片描述

解决方案1:cors
后端配置响应头
解决方案2:jsonp
只能解决 get跨域问题,前后端都要改变
解决方案3:代理服务器
1、后端:nginx
2、前端:vue-cli

在这里插入图片描述

配置代理服务器参考:https://cli.vuejs.org/zh/config/#devserver-proxy

代码演示

vue配置文件:vue.config.js
在这里插入图片描述

const{ defineConfig} =require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,
  lintOnSave:false,//关闭语法检查
  // 开启代理服务器(方式一)
  // devServer:{
  //proxy:'http://localhost:9091'
  //},
  // 开启代理服务器(方式二)
  devServer:{proxy:{'/proxy':{target: 'http://localhost:9091',
        pathRewrite:{'^/proxy':''},
        //ws: true,//用于支持websocket
        //changeOrigin: true //用于控制请求中的Host值,默认为true(说不说谎)}}}})

axios请求演示:

axios.get('http://localhost:8080/proxy/home/getHome').then(
        response =>{
          console.log('请求成功了',response.data)},
        error =>{'请求失败了',error.msg})

app组件

<template>
  <div class="app">
    <h1>{{msg}}</h1>
    <School:getSchoolName="getSchoolName"/>
    <!-- <Studentv-on:atguigu="getStudentName"/> -->
    <Student ref="student"/>
    <!-- vue中借助ruoter-link 标签实现路由的切换 -->
    <!-- <router-link active-class="active" to='/about'>About</router-link> -->
    <router-link active-class="active":to="{name:'guanyu'}">About</router-link>
    <br/>
    <router-link active-class="active" to="/home">Home</router-link>

    <div class="router_view">
      <router-view></router-view>
    </div>
    <button@click="getHome">获取主页信息</button>
  </div>
</template>

<script>
import School from'./components/School'
import Student from'./components/Student'
import axios from'axios'

export default{name: 'App',
  components:{
    School,
    Student},
  data(){return{msg:'你好!'}},
  methods:{getSchoolName(name){
      console.log('app收到了schoole的数据:',name)},
    getStudentName(name){
      console.log('app收到了student的数据:',name)},
    demo(){
      console.log('demo绑定')},
    getHome(){axios.get('http://localhost:8080/proxy/home/getHome').then(
        response =>{
          console.log('请求成功了',response.data)},
        error =>{'请求失败了',error.msg})}},
  mounted(){
    this.$refs.student.$on('atguigu',this.getStudentName)
    this.$refs.student.$on('demo',this.demo)}}</script>

<style>
  .app{background-color: bisque;}.router_view{background-color: aliceblue;}
</style>

结果:
在这里插入图片描述

  • 作者:春风霓裳
  • 原文链接:https://blog.csdn.net/qq_43470725/article/details/125580698
    更新时间:2022-09-15 08:26:31