在 Nextjs 中未发送响应即可解析 API [英] API resolved without sending a response in Nextjs

查看:24
本文介绍了在 Nextjs 中未发送响应即可解析 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to make same changes in my nextjs project because my enpoint API doesn't support many calls and I would like to make a refresh from the original data every 3 min.

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

I implemented API from nextjs: I create a pages/api/data and inside I make the call to my endpoint, and in my getInitialProps inside index call to data file.

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

The get works okey, but I have 2 problems:

1:我收到一条警告消息:

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

API resolved without sending a response for /api/data, this may result in stalled requests.

2: 3 分钟后不会重新加载数据.我想这是因为 Cache-Control 值...

2: It dosen 't reload data after 3 min..I supouse it is beacuse Cache-Control value...

这是我的代码:

页面/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();
    });
};

页面/索引

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;

推荐答案

你应该返回一个 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();
        resolve(); // in case something goes wrong in the catch block (as vijay commented)
      });
  });
};

这篇关于在 Nextjs 中未发送响应即可解析 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆