解决axios的post请求后端无参数传入或undefined问题以及vue页面跳转传参问题

 解决axios的post请求后端无参数传入或undefined问题以及vue页面跳转传参问题

 

main.js中引入axios

import axios from 'axios';
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$axios = axios;

 

login.vue组件methods中写入axios的post请求

    post_login() {
      var u = document.getElementById("username").value;
        // 获得标签属性id="username"的数据赋值给u
      var p = document.getElementById("password").value;
      const url ="接口url";
      var params = new URLSearchParams();  
      params.append("u", u);
      params.append("p", p);
    // 通过URLSearchParams()改变上传的参数格式为u=%E8%BF%AA%E8%BF%A6&p=123456
      this.$axios({
        method: "post",
        url: url,
        params,
      }).then((res) => {
        if (200 == res.data.code) {
        // 根据后端定义成功的正常请求,返回code值200为请求成功
          console.log(res.data);
          this.$message({
        // 定义一个type: "success",消息弹窗
            showClose: true,
            message: "登录成功 !",
            type: "success",
            duration: 2000,
          });
          this.$router.push({
        // this.$router.push跳转到path路径main.vue页面
            path: "/main",
            query: {
        // query将获取的后端数据res.data往下个网页传送
              name: res.data.name,
              author_face: res.data.author_face,
         // 将数据res.data.author_face包装到变量author_face
            },
          });
        } else {
          console.log(res.data);
          this.$message({
            showClose: true,
            message: "账号/密码错误,请重新输入 !!!",
            type: "error",
          });
        }
      });
    },

 通过URLSearchParams()改变上传的参数格式为u=%E8%BF%AA%E8%BF%A6&p=123456

使用情景:在后端接受不到前端post的json格式参数时

main.vue组件created中写入

  created() {
    this.name = this.$route.query.name;
    this.author_face = this.$route.query.author_face;
  },
// 通过this.$route.query.参数_name在created里初始化上个页面传来的参数

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值