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

相关推荐
富婆苗子几秒前
关于wangeditor的自定义组件和元素
前端·javascript
顾辰逸you2 分钟前
uniapp--咸虾米壁纸(三)
前端·微信小程序
北鸟南游6 分钟前
用现有bootstrap的模板,改造成nuxt3项目
前端·bootstrap·nuxt.js
前端老鹰7 分钟前
JavaScript Intl.RelativeTimeFormat:自动生成 “3 分钟前” 的国际化工具
前端·javascript
梦想CAD控件8 分钟前
(在线CAD插件)网页CAD实现图纸表格智能提取
前端·javascript·全栈
木子雨廷25 分钟前
Flutter 开发一个plugin
前端·flutter
重生之我是一名前端程序员28 分钟前
websocket + xterm 前端实现网页版终端
前端·websocket
sorryhc29 分钟前
【AI解读源码系列】ant design mobile——Space间距
前端·javascript·react.js
uhakadotcom44 分钟前
NPM与NPX的区别是什么?
前端·面试·github
GAMC1 小时前
如何修改node_modules的组件不被install替换?可以使用patch-package
前端