Vue中实现post和get方式提交数据可使用Axios很方便的实现,Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
1.安装axios
npm install --save axios
2.在main.js中引入并使用该模块,并设置域名(以后的请求都将基于该域名)
import axios from 'axios'
Vue.prototype.$http=axios.create({
baseURL: 'https://www.longdatech.com',
})
3.使用post提交数据并获取返回结果
this.$http.post("/uset/login",{
userName:'admin',
password:'123'
}).then(res=>{
console.log("返回结果:" + res);
if(res.code==0){
that.$message.success('登录成功')
}else {
that.$message.error('登录失败')
}
}).catch(error=>{
that.$message.error('登录失败')
})
4.使用get提交数据并获取返回结果
this.$http.get("/user/getUserInfo",{
params:{
id:'1'
}
}).then(res=>{
if(res.code==0){
that.$message.success('查询成功')
}else {
that.$message.error(res.message||'查询失败')
}
}).catch(error=>{
that.$message.error('查询失败')
})
5.请求其他域名下的接口
this.$http.get("http://127.0.0.1:8888/user/check?id=1").then(function(res){
// console.log(res.data);
},function(res){
// console.log(res);
});
参考:[Axios介绍(https://www.kancloud.cn/yunye/axios/234845)]