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错误返回值。
小智 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
例子:
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)
您可以尝试将以下附加导出添加到“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