在 Nextjs 中未发送响应的 API 已解析

Phi*_*hil 13 javascript rest node.js reactjs next.js

我必须在我的 nextjs 项目中进行相同的更改,因为我的 enpoint API 不支持很多调用,我想每 3 分钟刷新一次原始数据。

我从 nextjs 实现了 API:我创建了一个pages/api/data并在内部调用了我的端点,并在我的getInitialProps内部索引调用中调用了数据文件。

get 工作正常,但我有两个问题:

1:我有警告消息说:

API 在不发送 /api/data 响应的情况下解析,这可能会导致请求停止。

2:它在 3 分钟后没有重新加载数据......我认为这是因为缓存控制值......

这是我的代码:

页面/API/数据

import { getData } from "../../helper";

export default async function(req, res) {
  getData()
    .then(response => {
      res.statusCode = 200
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Cache-Control', 'max-age=180000');
      res.end(JSON.stringify(response))
    })
    .catch(error => {
      res.json(error);
      next();
    });
};
Run Code Online (Sandbox Code Playgroud)

页/索引

import React, { useState, useEffect } from "react";
import fetch from 'isomorphic-unfetch'

const Index = props => {

  return (
    <>Hello World</>
  );
};

 Index.getInitialProps = async ({ res }) => {
  const response = await fetch('http://localhost:3000/api/data')
  const users = await response.json()
  return { users }
};

export default Index;
Run Code Online (Sandbox Code Playgroud)

jfu*_*unk 14

对我来说,结果是必要的return,即使结果提供给客户时没有return

前: res.status(405).json({ message: 'Method not allowed.' });

之后,错误解决: return res.status(405).send('Method not allowed.');

[编辑]:更正为使用send而不是json错误返回值。

  • 不确定这一点,“.json”返回 void,并且不是异步的,因此它与普通返回没有太大区别,不是吗? (2认同)

小智 13

import { getData } from "../../helper";

export default async function (req, res) {
  try {
    const response = await getData();
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Cache-Control', 'max-age=180000');
    res.end(JSON.stringify(response));
  }

  catch (error) {
    res.json(error);
    res.status(405).end();
  }
}
Run Code Online (Sandbox Code Playgroud)


Nax*_*s84 10

您应该返回一个 Promise 并解决/拒绝它。

例子:

import { getData } from "../../helper";

export default async function(req, res) {
  return new Promise((resolve, reject) => {
    getData()
      .then(response => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Cache-Control', 'max-age=180000');
        res.end(JSON.stringify(response))
        resolve();
      })
      .catch(error => {
        res.json(error);
        res.status(405).end();
        return resolve(); //in case something goes wrong in the catch block (as vijay) commented
      });
  });
};
Run Code Online (Sandbox Code Playgroud)

  • 从异步函数返回承诺是多余的。最好在“getData”上使用“await”,放弃所有嵌套,并返回您想要的任何值,而不是“resolve”。 (7认同)
  • 我完全同意在“async”函数中返回显式的“Promise”并不总是必要的。但在我看来,如果我们使用“await”,则返回没有任何用处。这里的问题是 NextJS 只想要该函数的一些返回值,无论它是什么。返回类似“data.someValue”的内容可能会令人困惑。 (2认同)
  • 我有同样的错误。我忘记在 api 默认函数内的异步函数前面添加 `await`。 (2认同)

And*_*rey 5

您可以尝试将以下附加导出添加到“pages/api/xxxx”API 页面:

// pages/api/xxxx

export const config = {
  api: {
    externalResolver: true,
  },
};
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关以下配置的更多详细信息:
https ://nextjs.org/docs/api-routes/request-helpers#custom-config