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

相关推荐
前端付豪3 分钟前
项目启动:搭建Vue 3工程化项目
前端·javascript·vue.js
im_AMBER21 分钟前
React 07
前端·笔记·学习·react.js·前端框架
Giant10027 分钟前
Node.js .env 配置指南:安全管理项目秘钥与多环境适配
前端
沢田纲吉30 分钟前
《LLVM IR 学习手记(七):逻辑运算与位运算的实现与解析》
前端·c++·编译器
Giant10030 分钟前
小白也能懂:网页一堆 JS 变慢了?附具体代码优化方案
javascript
秋田君34 分钟前
3D热力图封装组件:Vue + Three.js 实现3D图表详解
javascript·vue.js·3d·three.js·热力图
golang学习记41 分钟前
从0死磕全栈之Next.js 重定向全指南:从基础跳转到大规模路由迁移
前端
Mapmost1 小时前
Mapmost地图引擎丨测绘资质“合规门票”
前端
JarvanMo1 小时前
不要在 SwiftUI 中使用 .onAppear() 进行异步(Async)工作——这就是它导致你的 App 出现 Bug 的原因。
前端
Moment1 小时前
Next.js 16 新特性:如何启用 MCP 与 AI 助手协作 🤖🤖🤖
前端·javascript·node.js