Springboot和Vue的前后端分离

首先创建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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LeeGaKi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值