现在有个接口localhost:5000/students,可以获取学生信息
现在vue写一个按钮获取学生信息
因为游览器的协议规定,不同端口导致跨域问题
解决方案一
使用代理服务器,首先在项目中创建配置文件
vue.config.js的配置内容
module.exports={
pages:{
index:{
// 入口
entry:'src/main.js',
},
},
lintOnSave:false, // 关闭语法检查
// 开启代理服务器
devServer:{
proxy:'http://localhost:5000'
}
}
改为本地端口
效果
方案二
如果有多个不同端口的服务器,那么方案一就不太能满足多个服务器。
vue.config.js的配置内容
module.exports={
pages:{
index:{
// 入口
entry:'src/main.js',
},
},
lintOnSave:false, // 关闭语法检查
// 开启代理服务器(方法一)
// devServer:{
// proxy:'http://localhost:5000'
// }
// 开启代理服务器(方法二)
devServer:{
proxy:{
'/api1':{
target:'http://localhost:5000',
pathRewrite:{'^/api1':''}, // 重写uri,替换为空字符串
ws:true, // 用于支持websocker
changeOrigin:true // 用于控制请求头的host值
},
'/api2':{
target:'http://localhost:5001',
pathRewrite:{'^/api2':''}, // 重写uri,替换为空字符串
ws:true, // 用于支持websocker
changeOrigin:true // 用于控制请求头的host值
}
}
}
}
改写访问路径
<template>
<div id="app">
<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/api1/students').then(
response=>{
console.log('请求成功',response.data)
},
error=>{
console.log('请求失败',error.message)
}
)
},
getCars(){
axios.get('http://localhost:8080/api2/cars').then(
response=>{
console.log('请求成功',response.data)
},
error=>{
console.log('请求失败',error.message)
}
)
}
}
}
</script>
效果