node.js - 不能重复请求

标签 node.js express

所以,我设置了这个路由,它从内部 API 获取 JSON 数据并显示它。我第一次访问该路由时,我得到了正确的 JSON 数据,但当我刷新页面时,我收到错误,并且页面只是卡在加载中。有什么想法吗?
注意:我使用请求 promise

app.get('/',function(req,res){
var options = {
//Here I initiate the API call.I actually have a url here.
uri: '',
json: true   
};

request(options)
    .then(function(data) {
        res.json(data);
        res.end();
    })
    .catch(function (err) {
        console.log(err);
    });
});

最佳答案

您在控制台中收到错误,并且页面卡住加载,因为您调用的 api 给出了错误响应,但您没有在 catch 回调中发送任何内容。试试这个。

  app.get('/',function(req,res){
    var options = {
        //Here I initiate the API call.I actually have a url here.
        uri: '',
        json: true   
    };

    request(options)
        .then(function(data) {
            res.json(data);
            res.end();
        })
        .catch(function (err) {
            console.log(err);
            res.status(500).send(err); // set proper error code and send response here
        });
  });

关于node.js - 不能重复请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854309/

相关文章:

javascript - Node/Express Js如何从 Angular 获取ajax参数

javascript - 如何使用 node.js 中的请求以多部分形式数据发送对象

javascript - 公开应用程序(由 Node.js 和 Redis 组成)的设置

node.js - Cassandra:操作超时

javascript - 找不到包含包含文件

unit-testing - 使用 JEST 测试快速路线

javascript - 如何清除req.session.array?

javascript - 将数据从数据库返回到 Controller

javascript - 使用 postgres 作为 Db 执行 app.get 时 Node.js 出现 404 错误

javascript - 如何在使用 nodejs 和 babel 进行集成测试时 stub 导入模块中的函数