【问题标题】:NextJS - how to configure proxy to log api requests and responses?NextJS - 如何配置代理来记录 api 请求和响应?
【发布时间】:2022-01-09 02:42:33
【问题描述】:

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

他们的建议之一是使用 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。

【问题讨论】:

    标签: proxy next.js cloudinary charles-proxy


    【解决方案1】:

    尝试以下方法:

    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 中转到 Proxy > Proxy Settings。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2018-12-20
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多