null is not an object (evaluating ‘u.data.data.c...(Cannot read property ‘content‘ of null)

null is not an object
(evaluating 'u.data.data.c...
Cannot read property 'content' of null

现在假设我们的token是无效的,比如我把token改成kkk,这时token就是无效的,就会出现上述报错。
在这里插入图片描述

1、console.log(‘response:’, response);

{
  "response": {
    "data": {
      "code": 7,
      "msg": "缺少token, 或无效token, 或token过期",
      "data": null
    },
    "header": {
      "Cache-Control": "no-cache, no-store, max-age=0, must-revalidate",
      "Content-Encoding": "gzip",
      "Content-Type": "application/json;charset=UTF-8",
      "Date": "Fri, 06 Dec 2024 06:21:34 GMT",
      "Expires": "0",
      "Pragma": "no-cache",
      "Strict-Transport-Security": "max-age=31536000 ; includeSubDomains",
      "Transfer-Encoding": "chunked",
      "X-Content-Type-Options": "nosniff",
      "X-Frame-Options": "DENY",
      "X-XSS-Protection": "1; mode=block",
      "vary": "accept-encoding"
    },
    "statusCode": 200,
    "cookies": [],
    "accelerateType": "none",
    "errMsg": "request:ok"
  },
  "__proto__": {}
}

2、console.log(‘response.data:’, response.data);

{
  "code": 7,
  "msg": "缺少token, 或无效token, 或token过期",
  "data": null
}

3、console.log(‘response.data.data:’, response.data.data);

response.data.data: null

4、index.js

const { baseUrl } = require('../../config/config');
const config = require('../../config/config')
import { calcViewHeight, iPhone } from '~/utils/device'
const { getToken } = require('../../utils/auth'); // 导入 getToken 方法

const { fetchSwiperImages } = require('../../utils/swiperService');
const app = getApp();

Page({
    data: {
      swiperImages:[
      ],// 初始化轮播图数据
      loading:true,
      cardLayout: 'grid',  // 默认卡片布局为网格模式
      isGrid: true,  // 默认为网格布局
      currentFilter: 'all', // 默认选中 all
      products:[
        
      ],   //存储从后端获取的商品数据
      searchValue: '',
      results: [],
      showBottomImage: false, // 控制底部图片的显示状态
      page: 0, // 当前页码
      size: 10, // 每页大小
      hasMore: true, // 是否还有更多数据
    },

        onReachBottom: function() {
          if (this.data.hasMore) {
            this.fetchData(this.data.currentFilter, this.data.page + 1, this.data.size);
          } else {
            wx.showToast({
              title: '没有更多数据了',
              icon: 'none'
            });
          }
          // 用户滑动到页面底部时触发
          this.setData({
            showBottomImage: true
          });
        },
      
    handleFilterClick: function(e) {
        const filterType = e.target.dataset.type;
        this.setData({
          currentFilter: filterType,
          page: 0, // 重置页码
          hasMore: true, // 重置是否有更多数据标志
          products: [] // 清空当前商品列表
        });
        this.fetchData(filterType);
    },
    // 处理网格视图按钮点击事件
    handleGridViewClick: function() {
        const currentLayout = this.data.cardLayout;
        const newLayout = currentLayout === 'grid' ? 'list' : 'grid';
    
        this.setData({
          cardLayout: newLayout,
          isGrid: !this.data.isGrid
        });
    },
    
    // 发送请求获取数据
    async fetchData(filterType, page = 0, size = 10) {
      try {
        const token = await getToken();
        console.log("获取商品数据前需要携带token=" + token);

        if (!token) {
          wx.showToast({
            title: '获取 token 失败,请重试',
            icon: 'none'
          });
          return;
        }

        const response = await new Promise((resolve, reject) => {
          wx.request({
            url: config.baseUrl + config.getAllProductsUrl, // 使用配置文件中的URL
            method: 'GET',
            data: { page, size }, // 分页参数
            header: { 'token': token },
            success: resolve,
            fail: reject
          });
        });

        console.log('response:', response); // 添加这一行来检查响应数据
        console.log('response.data:', response.data);
        console.log('response.data.data:', response.data.data);
        
        if (response.statusCode === 200) {
          // 检查 response.data 是否存在
          // if (!response.data || !response.data.data) {
          //   wx.showToast({
          //     title: '数据格式错误',
          //     icon: 'none'
          //   });
          //   return;
          // }
          const products = response.data.data.content || [];
          const formattedProducts = products.map(product => ({
            ...product,
            image: `${config.imageBaseUrl}${product.image}`
          }));

          const filteredProducts = formattedProducts.filter(product =>
            product.status === 1 && product.editAuth === 1
          );

          const truncatedNames  = filteredProducts.map(product => ({
            ...product,
            name: this.truncateString(product.name, 41) // 截断商品名称
          }));

          this.setData({
            // products: [...this.data.products, ...filteredProducts],
            products: [...this.data.products, ...truncatedNames ],
            loading: false, // 如果有加载指示器,设置为false
            hasMore: filteredProducts.length === size, // 是否还有更多数据
            page:page //更新页面数据中的page值
          });

          if (filteredProducts.length < size) {
            wx.showToast({
              title: '没有更多数据了',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        }
      } catch (error) {
        wx.showToast({
          title: error.message || '请求失败',
          icon: 'none'
        });
      }
    },
      // 截断字符串的方法
      truncateString(str, num) {
        if (str.length <= num) {
          return str;
        }
        return str.slice(0, num) + '...';
      },
    onLoad: function() {
      // this.loadSwiperImages(); // 调用新的方法获取轮播图数据
      this.fetchData('all'); // 默认加载“综合”数据
    },

      // 处理输入框的输入事件
      handleSearchInput: function (e) {
        this.setData({
          searchValue: e.detail.value // 更新输入框的值
        });
      },

      // 处理搜索事件(按下回车时)
      handleSearch: function () {
        const value = this.data.searchValue; // 获取输入的值
        if (!value) {
          wx.showToast({
            title: '请输入搜索内容',
            icon: 'none'
          });
          return;
        }
            // 获取 token 并跳转到结果页面
            getToken().then((token) => {
                if(!token){
                    wx.showToast({
                      title: '获取 token 失败,请重试',
                      icon: 'none'
                  });
                  return;
                }
                // 跳转到另一个页面,并传递搜索内容和 token
                wx.navigateTo({
                    url: `/pages/searchResults/searchResults?value=${value}&token=${token}`
                }); 
            }).catch((err)=>{
                  // 获取 token 失败时,在这里处理错误
                  wx.showToast({
                      title: '获取 token 失败,请重试',
                      icon: 'none'
                  });
            })
      },

      // 点击商品卡片后跳转到详情页
      navigateToDetail(event) {
        const productId = event.currentTarget.dataset.id;
        wx.navigateTo({
          url: `/pages/productDetail/productDetail?id=${productId}`,
        });
      },
       
      // 扫描二维码
      scanQrcode: function() {
        wx.scanCode({
          onlyFromCamera: false,  // 允许从相机和相册中选择图片
          success: (res) => {
            const jancode = res.result;
            console.log("扫描结果:", jancode);
            this.getProductByJancode(jancode);
          },
          fail: (err) => {
            wx.showToast({
              title: '扫描失败,请重试',
              icon: 'none'
            });
          }
        });
      },

      // 根据条码查询产品信息
      getProductByJancode: function(jancode) {
        getToken().then((token) => {
          if (!token) {
            wx.showToast({
              title: '获取 token 失败,请重试',
              icon: 'none'
            });
            return;
          }
          wx.request({
            url: `${config.baseUrl}/product/admin/detailByJancode`, // 使用配置文件中的URL
            method: 'GET',
            data: {
              jancode: jancode
            },
            header: {
              'token': `${token}`
            },
            success: (res) => {
              console.log("res=" + res);
              console.log("后端返回的数据:", res.data); // 添加日志输出
              if (res.statusCode === 200 && res.data && res.data.data) {
                const product = res.data.data;
                if (product) {
                  // 显示产品信息
                  this.setData({
                    products: [product],
                    showNoResultsImage: false // 如果有结果,隐藏无结果图片
                  });
                } else {
                  // 没有找到产品
                  wx.showToast({
                    title: '未找到该条码对应的产品',
                    icon: 'none'
                  });
                  this.setData({
                    showNoResultsImage: true // 如果没有结果,显示无结果图片
                  });
                }
              } else {
                wx.showToast({
                  title: '数据加载失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              wx.showToast({
                title: '请求失败',
                icon: 'none'
              });
            }
          });
        }).catch((err) => {
          wx.showToast({
            title: err.message,
            icon: 'none'
          });
        });
      },
      // 用户点击右上角分享按钮时触发(分享给朋友)
      onShareAppMessage: function (res) {
        // return {
        //   title: '自然的承诺,奢华的保鲜',
        //   path: 'pages/index/index', // 分享的路径,可以带参数
        //   imageUrl: '/icons/shareLOGO.png', // 分享的图片 URL
        //   success: function () {
        //     wx.showToast({
        //       title: '分享成功',
        //       icon: 'success',
        //       duration: 2000
        //     });
        //   },
        //   fail: function () {
        //     wx.showToast({
        //       title: '分享失败',
        //       icon: 'none',
        //       duration: 2000
        //     });
        //   }
        // };
      },

      // 用户点击右上角分享按钮时触发(分享到朋友圈)
      onShareTimeline: function (res) {
        return {
          title: '自然的承诺,奢华的保鲜',
          //query: 'param1=value1&param2=value2', // 分享的查询参数
          imageUrl: '/icons/shareLOGO.png', // 分享的图片 URL
          success: function () {
            wx.showToast({
              title: '分享成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: function () {
            wx.showToast({
              title: '分享失败',
              icon: 'none',
              duration: 2000
            });
          }
        };
      }

})



在JavaScript中,null 是一个表示“缺少值”或“默认情况”的特殊值。它通常用于表示缺少对象或默认情况。当你尝试访问 null 的属性或方法时,由于 null 不是对象,因此会抛出错误。
具体来说,尝试执行 null.content 会返回一个 TypeError 错误。错误信息可能是类似这样的:

TypeError: Cannot read property 'content' of null

这个错误表示你试图从 null 值中读取 content 属性,但 null 不是对象,所以没有属性可以读取。
要避免这种错误,你可以在访问属性之前检查变量是否为 nullundefined

if (variable !== null && variable !== undefined) {
  console.log(variable.content);
} else {
  console.log("variable is null or undefined");
}

这样,如果变量是 nullundefined,代码就不会尝试访问其属性,从而避免了 TypeError


在JavaScript中,如果你尝试访问 null 对象的属性,例如 null.content,会抛出一个错误。这是因为 null 是一个特殊的值,表示“没有对象”,它不是一个有效的对象实例,因此不能访问其属性。

错误类型

当你尝试访问 null 对象的属性时,会抛出以下错误:

  • TypeError: Cannot read property ‘content’ of null

示例代码

let obj = null;
console.log(obj.content);

错误信息

TypeError: Cannot read property 'content' of null
    at <anonymous>:2:13

解释

  1. null 的含义:

    • 在JavaScript中,null 表示一个空值或“无对象”。它是一个原始类型,表示变量没有指向任何对象。
  2. 访问属性:

    • 当你尝试访问 null 对象的属性时,JavaScript 解释器会尝试读取 null 的属性,但由于 null 不是对象,因此会抛出 TypeError
  3. 调试建议:

    • 在访问对象的属性之前,最好先检查该对象是否为 nullundefined。例如:
    let obj = null;
    
    if (obj && obj.content) {
        console.log(obj.content);
    } else {
        console.log("对象不存在或没有 content 属性");
    }
    

    这样可以避免程序因访问 nullundefined 的属性而崩溃。

总结

在JavaScript中,尝试访问 null 对象的属性会导致 TypeError,因为 null 不是对象,无法访问其属性。为了避免这种情况,应该在访问对象属性之前进行适当的空值检查。


在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值