axios post表单给laravel处理

随笔写个demo

vue前端方法发起axios的post请求

    login() {
      this.axios({
        method: "post",
        url: "http://api.arcxingye.cn:1234/api/dologin",
        data: {
          name: this.username,
          pass: this.password,
        },
        //转换数据让laravel能直接读取
        transformRequest: [
          function (data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURI(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          },
        ],
        //改header,默认的会出现问题
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
        //简单处理接收返回数据($message是element-ui的)
        .then((res) => {
          if (res.data == "true") {
            this.$message({ message: "登录成功", type: "success" });
            this.$router.push("/admin");
          } else {
            this.$message.error("用户名或密码不正确");
          }
        })
        .catch(() => {
          this.$message.error("登录失败");
        });

后端laravel接收处理数据

    public function dologin(Request $request){
        $user=$request->input('name');
        $pass=$request->input('pass');
        $data=user::where('name',$user)->where('password',$pass)->get();
        //简单搞一下处理后的返回
        if(count($data)==0){
        return array('false');}
        else{
            return array('true');
        }
    }

踩坑处:

1.原来还有transformRequest这种东西.jpg

2.axios请求头问题

点赞

发表回复

邮箱不会被公开,用于显示Gravatar的头像