简体   繁体   English

未从Node.js定义API请求

[英]API request is undefined from Nodejs

I'm working on my first CLI project and I'm having trouble getting it to execute API requests. 我正在做我的第一个CLI项目,但是我很难让它执行API请求。 I have tried fetch, axios, express, and a couple of npm packages, but I just can't figure out what's wrong. 我尝试了fetch,axios,express和几个npm软件包,但我只是想不出什么问题。 The project will console.log and gather user data from the command line, but will not retrieve API data. 该项目将console.log并从命令行收集用户数据,但不会检索API数据。 I'm using a fake API data url at this point just to be sure it works. 我现在使用的是伪造的API数据网址,只是为了确保它可以正常工作。 Here is the code: 这是代码:

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);

In the command line I get 'apiResponse: undefined' when I run the file. 在运行文件时,在命令行中显示“ apiResponse:undefined”。 Again, I've tried using several different libraries so I must be doing something fundamentally wrong. 同样,我尝试使用几种不同的库,因此我必须做的是根本上错误的事情。 The console.log OUTSIDE of the function prints, but neither console.logs INSIDE are printing. 该函数的console.log OUTSIDE可以打印,但是两个console.logs INSIDE都不能打印。 Any help would be greatly appreciated! 任何帮助将不胜感激!

I'm guessing in your console you see 我猜你在控制台上看到

undefined
Does this work?

The .get method is asynchronous, which means any assignment outside of then will most likely always be what you initialize it as, in this case nothing, or undefined . .get方法是异步的,这意味着以外的任何分配then将最有可能永远是你初始化它,在这种情况下什么都没有,或者undefined

Here's a high level of how things are actually happening: 这是事情实际发生的高度概述:

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

Here's one of many resources about Promises. 这是有关Promises 的众多资源之一

Move the log statement inside the .then() block. 将日志语句.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