使用 Fetch API 获取喜马拉雅用户信息并格式化输出

本示例演示如何使用 Fetch API 获取喜马拉雅用户信息,并使用 JavaScript 格式化输出用户信息,包括用户 ID、昵称、手机账号、会员到期时间、剩余天数和使用天数。

优化后的代码如下:

const getUserInfo = async () => {
  try {
    const response = await fetch('https://www.ximalaya.com/revision/main/getCurrentUser', {
      method: 'GET',
      mode: 'cors',
      credentials: 'include'
    });
    const data = await response.json();
    const userInfo = data.data;
    const { uid, nickname, mobile, vipExpireTime, totalVipDays } = userInfo;
    const expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + vipExpireTime);
    const formattedDate = `${expireDate.getFullYear()}-${expireDate.getMonth() + 1}-${expireDate.getDate()} 23:59:59`;
    console.log(`%c 用户 ID %c ${uid}`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
    console.log(`%c 用户昵称 %c ${nickname}`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
    console.log(`%c 手机账号 %c ${mobile}`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
    console.log(`%c 到期时间 %c ${formattedDate}`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
    console.log(`%c 剩余天数 %c ${vipExpireTime} 天`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
    console.log(`%c 使用天数 %c ${totalVipDays} 天`, 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 3px 0 0 3px; color: #fff; background: #40404c; font-weight: bold;', 'font-family: 微软雅黑;padding: 5px 4px; border-radius: 0 3px 3px 0; color: #fff; background: #e82b24; font-weight: bold;');
  } catch (error) {
    console.error(error);
  }
};

getUserInfo();

代码说明:

  1. 使用 async/await 语法简化异步操作,提高代码可读性。
  2. 使用结构化赋值语法简化从 userInfo 对象中提取属性的操作。
  3. 使用模板字面量格式化字符串,提高代码可读性。
  4. 使用 try...catch 语句处理潜在的错误。

示例代码展示了如何使用 Fetch API 获取喜马拉雅用户信息,并使用 JavaScript 格式化输出用户信息。

希望本示例能够帮助你理解如何使用 Fetch API 获取喜马拉雅用户信息并格式化输出。

使用 Fetch API 获取喜马拉雅用户信息并格式化输出

原文地址: https://www.cveoy.top/t/topic/lHWw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录