Javascript 如何通过express发送API响应
我目前正试图通过newsapi.org调用传递JSON结果。但是我不知道怎么做?任何帮助都会很好!!谢谢Javascript 如何通过express发送API响应,javascript,node.js,express,localhost,Javascript,Node.js,Express,Localhost,我目前正试图通过newsapi.org调用传递JSON结果。但是我不知道怎么做?任何帮助都会很好!!谢谢 newsapi.v2.topHeaders({ 类别:'一般', 语言:"en",, 国家:“非盟” })。然后(响应=>{ //控制台日志(响应); const respo=响应; }); app.get('/',函数(req,res){ res.send(respo); });如果希望在每个新请求中调用API,则应将其放入请求处理程序中: app.get('/', function (
newsapi.v2.topHeaders({
类别:'一般',
语言:"en",,
国家:“非盟”
})。然后(响应=>{
//控制台日志(响应);
const respo=响应;
});
app.get('/',函数(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);
});
如果希望在每个新请求中调用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);
});
您收到的错误是什么?你启动节点服务器了吗?它在哪个端口上运行?当您在浏览器中键入localhost:
时会发生什么?当您在索引路径:/
访问时会得到什么。您必须得到一个错误,该错误类型错误:未定义respo
。该newsapi调用必须在app.get(“/”)调用中,因为这是异步的。您的问题不完整,请确保向我们提供一个最小的可复制示例您收到的错误是什么?你启动节点服务器了吗?它在哪个端口上运行?当您在浏览器中键入localhost:
时会发生什么?当您在索引路径:/
访问时会得到什么。您必须得到一个错误,该错误类型错误:未定义respo
。该newsapi调用必须在app.get(“/”)调用中,因为这是异步的。您的问题不完整,请确保向我们提供最低限度的可复制示例