javascript - 如何通过 express 发送 API 响应
问题描述
我目前正在尝试从我的 newsapi.org 调用中传递 JSON 结果。但是我不知道该怎么做?任何帮助都会很棒!谢谢
newsapi.v2.topHeadlines({
category: 'general',
language: 'en',
country: 'au'
}).then(response => {
//console.log(response);
const respo = response;
});
app.get('/', function (req, res){
res.send(respo);
});
解决方案
如果您希望在每个新请求中调用 API,那么您可以将其放在请求处理程序中:
app.get('/', function (req, res){
newsapi.v2.topHeadlines({
category: 'general',
language: 'en',
country: 'au'
}).then(response => {
//console.log(response);
res.send(response);
}).catch(err => {
res.sendStatus(500);
});
});
如果您希望每隔一段时间调用一次 API 并缓存结果,那么您可以执行以下操作:
let headline = "Headlines not yet retrieved";
function updateHeadline() {
newsapi.v2.topHeadlines({
category: 'general',
language: 'en',
country: 'au'
}).then(response => {
headline = response;
}).catch(err => {
headline = "Error retrieving headlines."
// need to do something else here on server startup
});
}
// get initial headline
updateHeadline();
// update the cached headline every 10 minutes
setInterval(updateHeadline, 1000 * 60 * 10);
app.get('/', function (req, res){
res.send(headline);
});
推荐阅读
- jsf - 在 JSF 2.3 中通知用户会话结束
- linux - NCO netcdf4 操作 - ncwa(平均)
- python - 能够将字段保存到变量中并用于 queryset.value() 吗?django
- kotlin - 如何在 Kotlin 中惯用地调用可为空的 lambda?
- mongodb - 在 mongo 中应用 $filter 后,项目特定的嵌套数组属性
- python - Pandas:groupby 并创建一个新列,将聚合应用于两列
- javascript - 检查数组中的项目
- postgresql - PostgreSQL 为每个 array_agg 元素创建列而不是逗号分隔
- javascript - 如何使两个音频通道相交?
- typescript - 错误 TS2339:“功能”类型上不存在属性“名称”