NextJS - 如何配置代理以记录 api 请求和响应?

NextJS - how to configure proxy to log api requests and responses?

我在使用 Cloudinary Node SDK 时遇到问题,管理资源端点偶尔会抛出 302 错误。他们的支持建议我代理该请求,以便我可以记录我的 api 和他们的 SDK 之间的响应,并最终更好地了解可能导致问题的原因(最后他们希望看到 Location headers 在响应中)。

他们的一个建议是使用 Charles Proxy,但是我对它的工作原理还很陌生,无法理解。我通读了 Charles 文档并用了一整天的谷歌搜索,但我找不到任何与 NextJS API 和 Cloudinary SDK 之间的代理相关的信息。

我该如何设置 Charles Proxy 才能以这种方式查看请求和响应?还有另一种我不知道的方法可以代替吗?由于我使用的是最新版本的 NextJS v12,我可以改用新的 _middleware 选项吗?在后来的建议中,他们的支持也发表了这样的评论:

if you can't proxy requests to localhost, you may be able to use a local DNS server or a local override so you can access your local IP using a different hostname (e.g. using /etc/hosts on a unix environment, or C:\Windows\System32\Drivers\etc\hosts on a windows PC) and have that proxied - that said, there's probably an easier way using a Node project or adjusting the settings of the Node server.

但我也不知道从哪里开始。

这是我的 api 代码: pages/api/auth/images.ts

import type { NextApiRequest, NextApiResponse } from 'next';
import cloudinary from 'cloudinary';
require('dotenv').config();

export default async function handler(_: NextApiRequest, res: NextApiResponse) {
  cloudinary.v2.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
    secure: true,
  });

  try {
    // fetch cloudinary auth images
    const response = await cloudinary.v2.api.resources({
      type: 'upload',
      prefix: 'my_app/auth_pages',
      max_results: 20,
    });

    // fetch random image
    const randImage =
      response.resources[~~(response?.resources?.length * Math.random())];

    // return image
    return res.status(200).json({ image: randImage });
  } catch (error) {
    console.dir({ error }, { colors: true, depth: null });
    return res.status(500).json({ error });
  }
}

注意:我在Mac。

尝试以下操作:

export default async function handler(_: NextApiRequest, res: NextApiResponse) {
  cloudinary.v2.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
    api_proxy: 'http://<local_ip>:<charles_port>', //change accordingly
    secure: true,
  });

要获取端口号,请在 Charles Proxy 中转到代理 > 代理设置。