npm i axios
资料命令启动node server1和server2
运行server1.js:http://localhost:5000/students
const express = require('express')
const app = express()
app.use((request,response,next)=>{
console.log('有人请求服务器1了');
// console.log('请求来自于',request.get('Host'));
// console.log('请求的地址',request.url);
next()
})
app.get('/students',(request,response)=>{
const students = [
{id:'001',name:'tom',age:18},
{id:'002',name:'jerry',age:19},
{id:'003',name:'tony',age:120},
]
response.send(students)
})
app.listen(5000,(err)=>{
if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})
运行server2.js:http://localhost:5001/cars
const express = require('express')
const app = express()
app.use((request,response,next)=>{
console.log('有人请求服务器2了');
next()
})
app.get('/cars',(request,response)=>{
const cars = [
{id:'001',name:'奔驰',price:199},
{id:'002',name:'马自达',price:109},
{id:'003',name:'捷达',price:120},
]
response.send(cars)
})
app.listen(5001,(err)=>{
if(!err) console.log('服务器2启动成功了,请求汽车信息地址为:http://localhost:5001/cars');
})
vue-cli配置代理方式一(不完美)
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})
module.exports = {
lintOnSave: false ,//关闭语法检查
// 开启代理服务器
devServer:{
proxy:'http://localhost:5000'
}
}
src/App.vue
<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-cli配置代理方式二(不完美)
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})
module.exports = {
lintOnSave: false ,//关闭语法检查
// 开启代理服务器一(不完美)
// devServer:{
// proxy:'http://localhost:5000'
// }
devServer:{
proxy:{
'/api1':{// 匹配所有以'/api1开头的请求路径
target:'http://localhost:5000',//代理目标的基础路径
pathRewrite:{'^/api1':''}, // 代理往后端服务器的请求去掉/api1前缀
ws:true, //WebSocket
changeOrigin:true,
},
'/api2':{// 匹配所有以'/api2开头的请求路径
target:'http://localhost:5001',//代理目标的基础路径
pathRewrite:{'^/api2':''}, // 代理往后端服务器的请求去掉/api2前缀
ws:true, //WebSocket
changeOrigin:true,
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为: localhost:5000 说谎
changeOrigin设置为false时,服务器收到的请求头中的host为: localhost:8080 实话实说
*/
src/App.vue
<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/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>