栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决“微信小程序http请求参数为空时,传到java后端变成了undefined”问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决“微信小程序http请求参数为空时,传到java后端变成了undefined”问题

遇到问题:

最近在对接微信小程序和java后端springboot框架的接口,然后发现一个问题,当微信小程序发起http请求时,如果请求参数的值为空,传到java后端时就变成了undefined,这样情况如果后端程序员没有做来判断,就可能导致数据库查询失败。

原因分析:

1、先来看看我之前出错的js代码:

const app = getApp();
const http = require("../../utils/http.js");
Page({
	
	data: { 
		dataList:[]
	},
    //选择省
    ChangeProvinceCode(e){
      let name=e.target.dataset.name;
      this.setData({
        provinceName: name,
      })
      this.getCity()
    },
    //选择市
    ChangeCityCode(e){
      var that=this;
      let name=e.target.dataset.name;
      that.setData({
        cityName: name,
      })
      that.getDataList()
    },
    // 获取地点省
    getArea(){
      const that = this
      const params = {
        url: 'https://后端请求地址/selectArea',
        method: 'GET',
        callBack: function(res) {
          if(res.code == 200) {
            that.setData({
              AreaItems: res.data
            })
          }
        }
      }
      http.request(params)
    },
    // 获取地点市
    getCity(){
      const that = this
      const params = {
        url: 'https://后端请求地址/selectArea',
        method: 'GET',
        data:{
          pId: that.data.provinceId
        },
        callBack: function(res) {
          if(res.code == 200) {
            that.setData({
              Citytems: res.data
            })
          }
        }
      }
      http.request(params)
    },
    // 获取数据列表
    getDataList(){
      let that = this
      const params = {
          url: 'https://后端请求地址/getUserList',
          method: 'GET',
          data: {
            provinceName: that.data.provinceName, //省份
            cityName: that.data.cityName, //城市
          },
          callBack: res => {
              if(res.code==200){            
                that.setData({
                  dataList: res.data
                })
              }
          }
      }
      http.request(params)
    }, 
})

 2、getDataList()里需要传递2个参数到后端API接口请求数据,这两个参数需要用户在界面上选择省份或者城市后才可以获得。

3、问题来了,当用户没有选择省份和城市,我们去调用 getDataList()方法函数,provinceName和cityName这2个参数就是未定义的,传到java后端控制器变成了undefined

4、如果java后端没有判断参数值为undefined的情况,那么当我们的参数值为undefined时,就会查询不到需要的数据:

5、 参数真正为空时,查询的结果如下:

 6、是不是很神奇,哎,说不出的累 ~

解决方法: 

在页面的初始数据data: { }中定义查询的参数,这样就不会出现参数未定义就使用的情况,也就不会出现参数传到后端变为undefined这种问题了。

Page({

  
  data: { 
    dataList:[],
    provinceName:'',
    cityName:'',
  },

})

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754569.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号