zoukankan      html  css  js  c++  java
  • axios post 请求后端参数为null解决方案

    先看看官方教学请求写法

    axios.post('http://xxx.xxx.xxx.xxx:xxxx/xx', {'id': 'test'}).then(function (res) {
        console.log(res)
      }).catch(function (error) {
        alert(error)
      })

    结果后端接收到请求后,从HttpServletRequest获取的参数居然是null,这里记录一下,怎样解决这个问题,免得以后忘记,原因可以网上找找

    这是后端的接收请求代码

     @RequestMapping(value="/test",method= RequestMethod.POST)
        public String test(HttpServletRequest request){
            String id = request.getParameter("id");
            System.out.println(id);return "";
        }

    方法1:

    在前端发送axios的参数改成一个FromData对象,如下:

    var f = new FormData()
    f.append('id', 'test')
    
    axios.post('http://xxx.xxx.xxx.xxx:xxxx/xx', f).then(function (res) {
        console.log(res)
      }).catch(function (error) {
        alert(error)
      })

    方法2:

    使用方法1后,发现如果我已经有一个对象,每次请求都需要重新拆开里面的内容,重新放到FormData不就和麻烦,所以就找来了qs模块帮忙实现对象转换

    第一步就是安装qs

    npm install qs --save-dev

    第二步,引用qs

    import qs from 'qs'
    
    //Vue全局对象可用
    Vue.prototype.$qs = qs

    第三步调用

    var test = {'id', 'test'}
    
    //这里的this是Vue对象, axios.post(
    'http://xxx.xxx.xxx.xxx:xxxx/xx', this.$qs.stringify(test)).then(function (res) { console.log(res) }).catch(function (error) { alert(error) })

    总结:网上还有很多方式,不过本人觉得这个方式最容易,改动最少,所以就使用以上两种方法了,使用这两种方法就能后台就能成共获取到数据了

  • 相关阅读:
    html 简介
    MySQL事务等了解知识
    MySQL—navicat&&练习&&pymysql
    MySQL查询表(一)
    作业
    MySQL约束&&表关系
    mysql数据类型
    初识mysql
    dll 原理解析
    又过了一天
  • 原文地址:https://www.cnblogs.com/oscar1987121/p/10496537.html
Copyright © 2011-2022 走看看