当前位置: 首页 > article >正文

前端基础之ajax

vue-cli配置代理服务器解决跨域问题

我们可以使用一个代理服务器8080,Vue项目8080发送请求向代理服务器8080发送请求,再由在理服务器转发给后端服务器

首先需要在vue.config.js中配置代理服务器

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({

  transpileDependencies: true,

  lintOnSave: false,

  //开启代理服务器

  devServer:{

    proxy:'http://localhost:5000'

  }

})

然后将发送请求的axios路径改为代理服务器也就是改为8080

<template>

  <div>

    <button @click="getStudents">获取学生消息</button>

  </div>

</template>

<script>

import axios from 'axios';

export default {

  name: 'App',

  methods:{

    getStudents(){

      axios.get('http://localhost:8080/students').then(

        response=>{

          console.log('请求发送成功了',response.data)

        },

        error=>{

          console.log('请求失败了',error.message)

        }

      )

    }

  }

}

</script>

成功接收数据

多个代理配置

如果我们需要接收多个服务器传输的数据,就需要配置不止一个代理

在vue.config.js中

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({

  transpileDependencies: true,

  lintOnSave: false,

  devServer:{

    proxy:{

      '/atguigu':{

        target:'http://localhost:5000',

        pathRewrite:{'^/atguigu':''},

         ws:true,  //用于支持websocket

         changeOrigin:true //用于控制请求头中的host

      },

      '/demo':{

        target:'http://localhost:5001',

        pathRewrite:{'^/demo':''},

         ws:true,  //用于支持websocket

         changeOrigin:true //用于控制请求头中的host

      }  

    }

   

  }

})

进行发送请求

<template>

  <div>

    <button @click="getStudents">获取学生消息</button>

    <button @click="getCars">获取汽车消息</button>

  </div>

</template>

<script>

import axios from 'axios';

export default {

  name: 'App',

  methods:{

    getStudents(){

      axios.get('http://localhost:8080/atguigu/students').then(

        response=>{

          console.log('请求发送成功了',response.data)

        },

        error=>{

          console.log('请求失败了',error.message)

        }

      )

    },

    getCars(){

      axios.get('http://localhost:8080/demo/cars').then(

        response=>{

          console.log('请求发送成功了',response.data)

        },

        error=>{

          console.log('请求失败了',error.message)

        }

      )

    }

  }

}

</script>


http://www.kler.cn/a/574388.html

相关文章:

  • 人工智能直通车系列06【Python 基础与数学基础】(属性与方法概率论:概率基本概念)
  • 深入解析 Java 进程的内存占用-ByAI
  • MariaDB Galera 原理及用例说明
  • 键值对(C++实现)
  • vue2.6附件预览及下载
  • 大模型——基于 DIFY 的自动化数据分析实战
  • 爬虫逆向:脱壳工具 frida-dexdump 的使用详解
  • 安全见闻之网络安全新兴术语
  • 深度学习Save Best、Early Stop
  • 全面复习回顾——C++语法篇2
  • 华为OD机试-九宫格游戏(Java 2024 E卷 100分)
  • fetch为什么加了允许跨域请求mode: ‘no-cors‘,添加的多个header就丢失了?
  • java8 list分组
  • JavaWeb-idea配置smart tomcat
  • 大数据环境(单机版) Flume传输数据到Kafka
  • 算法之 前缀和
  • vector详解
  • netty中Future和ChannelHandler
  • 鸿蒙Next网络请求~上传文件pdf
  • SCI1区TOP:自适应学习粒子群算法SLPSO,深度解析+性能实测