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

相关推荐
拾光拾趣录16 分钟前
CSS常见问题深度解析与解决方案(第三波)
前端·css
徊忆羽菲24 分钟前
Echarts3D柱状图-圆柱体-文字在柱体上垂直显示的实现方法
javascript·ecmascript·echarts
轻语呢喃33 分钟前
JavaScript :字符串模板——优雅编程的基石
前端·javascript·后端
杨进军34 分钟前
React 协调器 render 阶段
前端·react.js·前端框架
中微子37 分钟前
Blob 对象及 Base64 转换指南
前端
风铃喵游37 分钟前
让大模型调用MCP服务变得超级简单
前端·人工智能
中微子38 分钟前
智能前端实践之 shot-word demo
前端
归于尽39 分钟前
智能前端小魔术,让图片开口说单词
前端·react.js
用户98738245810139 分钟前
vite 插件
前端
无数山41 分钟前
autorelease pool
前端