vue-vue2脚手架12-配置代理
ajax跨域问题
1. 纯js版本 xhr new XMLHttpRequest
xhr.open xhr.send
2.jQuery $.get $.post (80%都是封装dom操作,vue的作用就是封装dom)
3.axios 对xhr的封装,作者推荐使用
4.fetch 在ie上兼容较差
使用axios : npm i axios
跨域问题解决
- cors 服务端在请求添加http响应头
- jsonp scipet scr 只能巧妙避开 只能解决get请求
- 代理服务
- niginx 反向代理
- vue-cli
vue官网cli配置使用说明 https://cli.vuejs.org/zh/config/#devserver
在工程中添加 vue.config.js
vue.config.js
module.exports = {
pages: {
index: {
//入口
entry: 'src/main.js',
},
},
lintOnSave:false, //关闭语法检查
//开启代理服务器(方式一)
/* devServer: {
proxy: 'http://localhost:5000'
} */
//开启代理服务器(方式二)
devServer: {
proxy: {
'/demo': {
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''},
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值
},
'/': {
target: 'http://localhost:5000',
//pathRewrite:{'^/atguigu':''},
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值
},
}
}
}
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/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>
说明:
- 优点:配置简单,请求资源时直接发给前端(8080)即可。
- 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
- 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)