【问题标题】:Node axios don't save response in variable however it prints it in console节点 axios 不会将响应保存在变量中,但它会在控制台中打印它
【发布时间】:2018-12-17 11:40:54
【问题描述】:

我在节点中向 NewsAPI.org 发出 API 请求,如果我只是使用控制台日志,则会打印响应。现在我希望它在 var 'news' 中返回它并且它不返回它。此外,我在“updatedNews”中的函数返回仍然无法正常工作。

所以数据在控制台日志中返回,但没有保存在'var'中。

var news = 'news';

async function getNews() {
  var responseNews = await axios
    .get(
      "https://newsapi.org/v2/top-headlines?country=us&apiKey=key"
    )
    .then( response =>  news = response.data.articles );
    return responseNews;
}

var updatedNews = getNews()
console.log(news)
console.log(updatedNews)

【问题讨论】:

    标签: node.js axios


    【解决方案1】:

    你的代码有很多问题......

    1. 返回的响应是对象数组而不是字符串。
    2. 这不是 async / await 的工作方式等等等等。

    这应该可行:

    const axios = require('axios');
    
    async function getNews() {
      const response = await axios.get(
        'https://newsapi.org/v2/top-headlines?country=us&apiKey=key',
      );
    
      const news = response.data.articles;
      console.log(news);
    }
    
    getNews();
    

    【讨论】:

    • 我批准了你的回答,因为我认为提出请求的方法更短,我将阅读更多关于 JavaScript 中的同步和异步的内容。
    【解决方案2】:

    var updatedNews = getNews()

    在这里你进行异步调用,在下一行你期待结果。但是这里的异步调用尚未解决。我们可以实现这一点的方式在下面更新。 这是相同的更新代码。

    <!DOCTYPE html>
    <html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
    
    <body>
      <script>
        'use strict';
        var news = ""
    
        function f() {
          return axios
            .get(
              "https://jsonplaceholder.typicode.com/todos/1"
            )
            .then(response => response.data.title);
        }
    
        f().then(news => console.log(news));
      </script>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多