axios请求
Axios
1. 安装axios
npm i axios
//在需要请求接口的组件中引入 axios
import axios from 'axios'
2. 语法格式
created(){
//解决跨域问题时,如果在路径中写代理名,代理名也会成为路径
axios.get|post('请求路径',{
params:{
键:值,
键:值
}
}).then(res=>{
}).catch(err=>{
})
}
3. 跨域问题
跨域: 协议,域名,端口号有一个不一致就会产生跨域
1) 跨域说明
eg:
服务端: http://localhost:8090/index
客户端: http://localhost:8081/
上面端口号不一致 => 跨域
报错: Access to XMLHttpRequest at 'http://localhost:8091/index' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2) 解决跨域
Axios解决跨域方式: 写代理
设置代理:
找到vue.config.js配置文件
3) vue.config.js 写代理,解决跨域
module.exports={
devServer:{
port:9090, // 设置新端口号
// 设置代理
proxy:{
//直接写代理
'代理名':{
target:'要代理的服务器地址'
}
'/index':{
target:'http://localhost:8090'
},
// 如果需要自定义代理名,需要重写路径
'/api':{
target:'代理名',
pathRewrite:{
'^/api':''
}
}
'/api':{
target:'http://localhost:8090',
pathRewrite:{
"^/api":''
}
}
}
}
}
浙公网安备 33010602011771号