前端基础之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>

相关推荐
kyriewen1 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm1 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy2 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程
zhangxingchao2 小时前
多 Agent 架构到底怎么选?从 Claude Agent Teams、Cognition/Devin 到工程落地原则
前端·人工智能·后端
IT_陈寒2 小时前
SpringBoot那个自动配置的坑,害我排查到凌晨三点
前端·人工智能·后端
Honor丶Onlyou2 小时前
VS Code 右键菜单修复记录
前端
卡卡军2 小时前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust
PILIPALAPENG2 小时前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python
Larcher2 小时前
🔥 告别抓瞎:用 Claude Code (cc) 优雅接手与维护已有项目
javascript·机器学习·前端框架
JYeontu2 小时前
轮播图不够惊艳?试下这个立体卡片轮播图
前端·javascript·css