先用nodejs创建两个服务器端口自己随便设置
// 服务器1
var http = require('http')
// 创建一个web服务器
var server = http.createServer()
// 接收到客户端发过来的请求
server.on('request',function(request,response){
reData = [
{'name':'刘德华','age':31,'gender':'男'},
{'name':'杨幂','age':27,'gender':'女'},
{'name':'周星驰','age':40,'gender':'男'}
]
console.log('收到客户端请求,请求路径是:'+request.url)
response.setHeader("Content-Type","text/plain; charset=utf-8");
response.write(JSON.stringify(reData))
response.end()
})
// 启动服务器
server.listen(5000,function(){
console.log('服务器启动成功,可以通过127.0.0.1:5000进行访问')
})
// 服务器2
var http = require('http')
// 创建一个web服务器
var server = http.createServer()
// 接收到客户端发过来的请求
server.on('request',function(request,response){
reData = [
{'carName':'宝马','date':'2018','price':'100'},
{'carName':'奔驰','date':'1998','price':'200'},
{'carName':'路虎','date':'2008','price':'230'}
]
console.log('收到客户端请求,请求路径是:'+request.url)
response.setHeader("Content-Type","text/plain; charset=utf-8");
response.write(JSON.stringify(reData))
response.end()
})
// 启动服务器
server.listen(5001,function(){
console.log('服务器启动成功,可以通过127.0.0.1:5001进行访问')
})
启动服务器:
app.vue中演示代码:
<template>
<div id="app">
<HelloWorld/>
<button @click="getserver1">获取服务器1的数据</button>
<button @click="getserver2">获取服务器2的数据</button>
</div>
</template>
<script>
import axios from 'axios'
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
methods:{
getserver1(){
axios.get('http://127.0.0.1:8080/star').then(
response=>{
console.log(response.data)
},
error=>{
console.log(error)
}
)
},
getserver2(){
axios.get('http://127.0.0.1:8080/bus').then(
response=>{
console.log(response.data)
},
error=>{
console.log(error)
}
)
}
}
}
</script>
在vue.config.js中进行代理服务器设置
module.exports = {
pages:{
index:{
entry:'src/main.js',
}
},
lintOnSave:false,// 关闭语法检查
/*
devServer: {
proxy: 'http://127.0.0.1:5000'
}
*/
devServer: {
proxy: {
'/bus': {
target: 'http://127.0.0.1:5001',
ws: true,
changeOrigin: true
},
'/star': {
target: 'http://127.0.0.1:5000',
ws: true,
changeOrigin: true
}
}
}
}
效果: