【问题标题】:NextJS API not posting to external domainsNextJS API 未发布到外部域
【发布时间】:2021-04-03 02:28:19
【问题描述】:

我有一个在 Vercel 中运行的简单 NextJS 应用程序。我克隆了 Vercel 提供的 NextJS 模板,只添加了一个名为 jira.js 的文件

当这个 jira 被命中时,我只是想将随机数据发布到外部 API。

Jira.js 如下

    // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    
    import axios from 'axios'
    import https from 'https'
    
    export default (req, res) => {
        const headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }
    
        axios.post('https://webhook.site/6db7a14b-48d7-4037-a482-86885526aa40', {
            Name: 'Fred',
            Age: '23'
        }, {
            headers: headers,
            withCredentials: true
        }
        ).then(function(res) {
            console.log({res: res})
        }).catch(function(e) {
            console.log({"failed": e})
        })
        res.json({ status: 'ok' })
    
    }

当我在本地尝试 (localhost:3000/api/jira) 时,数据被发布到 Webhook 站点,但是当我将其部署到 vercel(random-domain.com/api/jira) 时,webhook 站点中没有数据发布,但我得到了状态:浏览器中的 ok 消息。

我对此很陌生? somoene 可以指导我了解我所缺少的吗?

【问题讨论】:

  • 光看这个很难看,但是,你检查过vercels仪表板中的功能日志吗?如果是这样,您能否查看console.log({"failed": e}) 是否被命中(控制台日志应该登录到 vercel),也许 axios 请求失败?

标签: node.js reactjs next.js vercel


【解决方案1】:

你还没有将你的函数标记为async,所以我不相信它正在等待 JIRA 的回复。例如:


export default async (req, res) => {
  try {
    const response = await fetch(
      `https://webhook.site/6db7a14b-48d7-4037-a482-86885526aa40`,
      {
        body: JSON.stringify({
            Name: 'Fred',
            Age: '23'
        }),
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json'
        },
        method: 'POST'
      }
    );

    if (response.status >= 400) {
      return res.status(400).json({
        error: 'There was an error'
      });
    }

    return res.status(200).json({ status: 'ok' });
  } catch (error) {
    return res.status(500).json({
      error: 'There was an error'
    });
  }
};

您也不需要axios - 默认情况下fetch 已为您填充。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多