首先创建SpringBoot项目 写好控制器
@RestController//返回字符串
@CrossOrigin//开启跨域请求
@RestController//返回字符串
@CrossOrigin//开启跨域请求
public class UserController {
@RequestMapping("/login")
public Map<String,Object> login(String name,String pwd){
Map<String,Object> map = new HashMap<>();
String admin = "admin";
String pass = "123";
if (admin.equals(name) && pass.equals(pwd)){
map.put("status",200);
map.put("user","name="+admin+"pass"+pass);
}else {
map.put("status",500);
map.put("msg","用户民或密码错误");
}
return map;
}
}
Vue项目中main.js全局导入
//全局导入axios和querystring
import * as axios from "axios";
import * as querystring from "querystring";
//在Vue中指定全局变量 为Vue设置全局变量的语法是Vue.prototype.$变量名=组件名
//使用的时候用this.$变量名
Vue.config.productionTip = false
Vue.prototype.$axios = axios
Vue.prototype.$querystring = querystring
异步发送Get请求和Post请求方式如下
<script>
export default {
name: "LoginPage",
data(){
return{
msg:""
}
},
methods:{
login:function (){
let username = document.getElementById("name").value;
let pwd = document.getElementById("pwd").value;
let path = "http://localhost:8081/login?name="+username+"&pwd="+pwd;
// let path = "http://localhost:8081/login";
//发送异步请求,then服务器返回如何处理,catch是服务器异常如何处理
//(变量=>{代码})
//post请求(请求地址?参数,querystring.stringify({json请求参数}))
//路径中的参数是可见的,querystring传递的参数不可见
//querystring是另外一个组件 Vue核心中的直接用
let params = {
name:username,
pwd:pwd
}
this.$axios.post(path,this.$querystring.stringify(params)).then(resp=>{
let result = resp.data;
console.log(resp)
if(result.status==200){
this.msg=''
alert("登陆成功")
}else {
this.msg=result.msg
}
}).catch(error=>{
console.log(error)
});
//get请求
this.$axios.get(path).then(resp=>{
let result = resp.data;
console.log(resp)
if(result.status==200){
this.msg=''
alert("登陆成功")
}else {
this.msg=result.msg
}
}).catch(error=>{
console.log(error)
});
}
}
}
</script>