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

相关推荐
dog shit35 分钟前
web第十次课后作业--Mybatis的增删改查
android·前端·mybatis
我有一只臭臭35 分钟前
el-tabs 切换时数据不更新的问题
前端·vue.js
七灵微39 分钟前
【前端】工具链一本通
前端
Nueuis2 小时前
微信小程序前端面经
前端·微信小程序·小程序
_r0bin_4 小时前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
IT瘾君4 小时前
JavaWeb:前端工程化-Vue
前端·javascript·vue.js
zhang98800004 小时前
JavaScript 核心原理深度解析-不停留于表面的VUE等的使用!
开发语言·javascript·vue.js
potender4 小时前
前端框架Vue
前端·vue.js·前端框架
站在风口的猪11085 小时前
《前端面试题:CSS预处理器(Sass、Less等)》
前端·css·html·less·css3·sass·html5
程序员的世界你不懂5 小时前
(9)-Fiddler抓包-Fiddler如何设置捕获Https会话
前端·https·fiddler