【问题标题】:How to pass information to the view after function completion when using NodeJS Request?使用NodeJS Request时如何在函数完成后将信息传递给视图?
【发布时间】:2016-10-28 03:34:20
【问题描述】:

我正在编写代码来获取一些 JSON 数据并将其传递到具有给定数据的新视图。 该视图名为 /newbook2,我想将书名、作者姓名等信息从通过 API 调用的 JSON 文件传递​​给视图。

var s_book_name;
var s_author_name;
var s_isbn13_id;
var s_publisher_name;
var s_category_id;
var error="";

router.post('/searchbook', function(req, res){

    var isbn=req.body.isbn;
    var url="http://isbndb.com/api/v2/json/63JEP95R/book/"+isbn;
    request({
    url: url,
    json: true
    }, function (error, response, body) {
          if (!error && response.statusCode === 200) {
                if(body.data[0].title!=null)
                  s_book_name=body.data[0].title;
                if(body.data[0].author_data[0]!=null)
                  s_author_name=body.data[0].author_data[0].name;
                if(body.data[0].isbn13!=null)
                  s_isbn13_id=body.data[0].isbn13;
                if(body.data[0].publisher_name!=null)
                  s_publisher_name=body.data[0].publisher_name;
                if(body.data[0].subject_ids[0]!=null)
                  s_category_id=body.data[0].subject_ids[0];
              }
          else error="Book not found. Please enter the information manually."
    });
    res.redirect('/newbook2');

    });

但是,我的视图中尚未加载信息。这似乎是异步调用的常见问题。但是,我是 nodejs 的新手,希望能提供有关如何修复它的任何帮助。

router.get('/newbook2', function(req, res){
    res.render('newbook2', {title: 'Add New Book',s_book: s_book_name, s_author: s_author_name, s_isbn13: s_isbn13_id ,s_publisher: s_publisher_name , s_category: s_category_id});
    });

【问题讨论】:

    标签: json node.js asynchronous


    【解决方案1】:

    您需要为此使用承诺。以下是一些示例代码供您参考以进行 POST 调用。

    router.post('/newBook', function(req, res, next) {
        console.log('Please add your here to get the data from server');
        Obj.then(function() {
            res.send('You got the success response from the server');
        });
    });
    

    res.send('Your Book has been successfully added.'); 只会在您从服务器获得成功响应后执行。 请通过 Promise 的概念了解更多详细信息。

    【讨论】:

    • 我收到了错误。任何线索为什么? /Users/shehzadlokhandwalla/shehzad/routes/index.js:85 .then(function() { ^ SyntaxError: Unexpected token .
    • 是的。那么基本上应该与 Promise 对象一起使用。我已经更正了答案中的语法。
    • 作为回答,我刚刚提供了伪代码。请自行使用正确的语法/代码。
    猜你喜欢
    • 2021-09-04
    • 2015-05-26
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多