簡體   English   中英

未從Node.js定義API請求

[英]API request is undefined from Nodejs

我正在做我的第一個CLI項目,但是我很難讓它執行API請求。 我嘗試了fetch,axios,express和幾個npm軟件包,但我只是想不出什么問題。 該項目將console.log並從命令行收集用戶數據,但不會檢索API數據。 我現在使用的是偽造的API數據網址,只是為了確保它可以正常工作。 這是代碼:

const axios = require('axios');

let apiResponse;

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    apiResponse = response;
    console.log('Does this work?')
  })
  .catch(function (error) {
    console.log(error, 'Error');
  });

console.log('apiResponse: ', apiResponse);

在運行文件時,在命令行中顯示“ apiResponse:undefined”。 同樣,我嘗試使用幾種不同的庫,因此我必須做的是根本上錯誤的事情。 該函數的console.log OUTSIDE可以打印,但是兩個console.logs INSIDE都不能打印。 任何幫助將不勝感激!

我猜你在控制台上看到

undefined
Does this work?

.get方法是異步的,這意味着以外的任何分配then將最有可能永遠是你初始化它,在這種情況下什么都沒有,或者undefined

這是事情實際發生的高度概述:

1) Create undefined var apiResponse
2) axios.get(...)
3) console.log(apiResponse)
4) #2 completes, assigns to `apiResponse`
5) End execution

這是有關Promises 的眾多資源之一

將日志語句.then()塊內。

const axios = require('axios');

let apiResponse;

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    apiResponse = response;
    console.log('Does this work?')
    console.log('apiResponse: ', apiResponse);
  })
  .catch(function (error) {
    console.log(error, 'Error');
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM