首页 > 解决方案 > 当id包含“/”时如何通过id使用GET

问题描述

我正在使用 Node.js 和 aws-sdk 构建一个 API,所以我有一个GET函数来通过IDKEY下载文件

export const downloadFile = async(req: Request, res: Response) => {
  const params = {
    Bucket: AWS_S3.Bucket,
    Key: req.params.key
  };

  res.setHeader('Content-Disposition', 'attachment');

  s3.getObject(params)
    .createReadStream()
    .on('error', error => {
      return res.status(500).json({
        message: 'Ocurrio un error al descargar el archivo',
        error
      });
    }).pipe(res);
}

问题在于键的名称,因为包含/并且 Node.js 认为这是一个新路由。

例子:

const URL_API = 'http://localhost:3000/api';
const KEY = '/mendozarq/images/example.jpg'

const URL = `${URL_API}/download/${KEY}`;

最后我得到了这个错误:

Cannot GET /api/download//mendozarq/images/example.jpg

标签: node.jstypescripthttp-getnodejs-server

解决方案


推荐阅读