You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js API中处理Base64编解码请求的实现方法问询

Next.js Base64编解码API实现方案

1. 创建API路由文件

在Next.js项目的pages/api目录下新建一个文件,比如encode-decode.js——Next.js会自动把这个文件映射为/api/encode-decode的API接口。

2. 核心实现思路

  • 利用Next.js内置的req.query直接获取URL中的查询参数,无需手动解析URL
  • 实现基础的Base64编解码函数(针对ASCII字符串)
  • 根据参数类型(encode或decode)调用对应函数,将结果以JSON格式返回
  • 处理参数缺失、编解码失败等异常情况

3. 完整代码实现

// pages/api/encode-decode.js

export default function handler(req, res) {
  // 设置响应头为JSON格式
  res.setHeader('Content-Type', 'application/json');

  // 获取URL参数
  const { encode, decode } = req.query;

  // 情况1:存在encode参数,执行编码
  if (encode) {
    try {
      // btoa仅支持ASCII字符串,若需处理Unicode可参考备注
      const encoded = btoa(encode);
      return res.status(200).json({
        success: true,
        original: encode,
        encoded: encoded
      });
    } catch (err) {
      return res.status(400).json({
        success: false,
        error: '编码失败:仅支持ASCII字符串'
      });
    }
  }

  // 情况2:存在decode参数,执行解码
  if (decode) {
    try {
      const decoded = atob(decode);
      return res.status(200).json({
        success: true,
        original: decode,
        decoded: decoded
      });
    } catch (err) {
      return res.status(400).json({
        success: false,
        error: '解码失败:无效的Base64字符串'
      });
    }
  }

  // 情况3:无有效参数
  return res.status(400).json({
    success: false,
    error: '请提供encode或decode参数,例如:?encode=hello 或 ?decode=aGVsbG8='
  });
}

4. 代码说明

  • 参数解析:req.query是Next.js自动解析后的URL参数对象,直接解构出encode和decode即可
  • 编码扩展:如果需要处理中文等Unicode字符,可替换编码逻辑为:
    const encoded = btoa(unescape(encodeURIComponent(encode)));
    
  • 解码异常处理:atob()遇到无效Base64字符串会抛出错误,用try/catch捕获后返回友好提示
  • 响应规范:统一返回JSON格式,包含success状态标识、结果数据或错误信息,便于前端处理

5. 测试方法

  • 编码测试:访问http://localhost:3000/api/encode-decode?encode=string_to_encode,会返回编码后的Base64字符串
  • 解码测试:访问http://localhost:3000/api/encode-decode?decode=c3RyaW5nX3RvX2VuY29kZQ==,会返回解码后的原ASCII字符串
  • 异常测试:不传参数或传入无效Base64内容,会返回对应的错误提示

内容的提问来源于stack exchange,提问作者Steven Rugg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:01:14