在 Nextjs 中未发送响应的 API 已解析 [英] API resolved without sending a response in Nextjs
问题描述
我必须在我的 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 工作正常,但我有两个问题:
The get works okey, but I have 2 problems:
1:我有一个警告消息:
API 已解析但未发送对/api/data 的响应,这可能会导致请求停滞.
API resolved without sending a response for /api/data, this may result in stalled requests.
2:它在 3 分钟后不会重新加载数据......我认为这是因为缓存控制值......
2: It dosen 't reload data after 3 min..I supouse it is beacuse Cache-Control value...
这是我的代码:
pages/api/data
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;
推荐答案
示例:
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
});
});
};
这篇关于在 Nextjs 中未发送响应的 API 已解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!