当我执行下面的代码片段时,终端返回控制台日志“函数调用”和“结束函数”,但不返回中间console.log(),就好像请求没有被执行一样。 有谁知道为什么吗?
export const retrieveData : Function = () => {
console.log('function called');
const url = `https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=${key}`;
axios.get(url,{
responseType: 'json',
headers: { 'User-Agent': 'request' }
})
.then(response => {
console.log('first step', response);
// return response.json();
return response;
})
.then(data => {
console.log('second step');
console.log(data)
return 'hola'
} )
.then(successMessage => {
console.log('success',successMessage);
})
.catch(error => console.error(`Error: ${error}`));
console.log('end function');
};
我使用相同的 url 和密钥测试了邮递员的端点,它工作得很好。
如果您致电
response = axios.get(url)
,
真正的数据是 response.data
而不是 response
是父模式。详细信息在这里
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
// As of HTTP/2 status text is blank or unsupported.
// (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4)
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
所以你必须返回这个格式
axios.get(url,
{
responseType: 'json',
headers: { 'User-Agent': 'request' }
})
.then(response => {
return response.data;
})
另存为
get-data.ts
文件。
const axios = require('axios');
export const retrieveData: Function = () => {
const key = 'your API key'
console.log('function called');
const url = `https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=${key}`;
axios.get(url,
{
responseType: 'json',
headers: { 'User-Agent': 'request' }
})
.then(response => {
return response.data;
})
.then(data => {
console.log(JSON.stringify(data, null, 4))
return 'hola'
})
.then(successMessage => {
console.log('success', successMessage);
})
.catch(error => console.error(`Error: ${error}`));
console.log('end function');
}
retrieveData();
tsc get-data.ts
node get-data.js
这有助于使 JSON 格式具有 4 个空格缩进以提高可读性。
JSON.stringify(data, null, 4)