如何调用外部API,然后从hapi.js Api中返回此数据 [英] How to call an external API then return this data from an in hapi.js Api
问题描述
我是Hapi.js节点扩展的新手.
I am new to the Hapi.js node extension.
我正在尝试将外部API调用到服务器中,因为外部API受CORS保护,并且无法从前端(角度9)进行调用.
I am trying to call an external API into my server because the external API is protected with CORS and I can't call it from my front (Angular 9).
所以我用路由等设置了我的hapi服务器,现在在一条路由中,我试图导入外部数据,并且当前端调用我的hapi api的路由时,它将显示来自外部API的数据.
So I set up my hapi server with routes etc and now in a route I am trying to import the external data and when the front call the route of my hapi api it show the data from the external API.
我没有找到任何文档或关于此问题的主题,如果您可以向我提供一些信息,那将非常有帮助!
I didn't find any documentation or already topics about this problem, if you could provide me with some information it would be very helpful!
(我想通过路由solcast进行外部API调用)
这是我的 index.js :
'use strict';
require('dotenv').config()
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost',
routes: {
cors: true
}
});
server.route(require('./routes/base').test);
server.route(require('./routes/solcast').solcast);
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
这是我的 solcast.js :
这在console.log时出现错误:
This while console.log the error :
Error: handler method did not return a value, a promise, or throw an error
然后console.log数据.我假设返回完成后未收到数据.
And then console.log the data. I assume that the data is not received when the return is done.
const joi = require('@hapi/joi');
const fetch = require("node-fetch");
exports.solcast = {
method: 'GET',
path: '/solcasttest',
handler: (request, h) => {
fetch("https://linkToTheExternalApi")
.then(response => response.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err))
console.log(testSolcast)
}
}
谢谢您的帮助,如果您需要任何其他信息,请联系我.
Thank you for your help, if you need any other information hit me up.
推荐答案
正如抛出的错误所暗示的那样, hapi.js
中的 handler
必须返回一个值,一个诺言或抛出错误.
As the error thrown suggests, a handler
in hapi.js
must return a value, a promise or throw an error.
在您的情况下, handler
是异步操作,因此您必须返回一个Promise.
In your case, the handler
is an asynchronous operation, so you have to return a promise.
由于 fetch
已经创建了一个承诺,如果您在处理程序中返回由 fetch
创建的承诺,就足够了:
As fetch
already creates a promise, it is enough if you return the promise created by fetch
in your handler :
const fetch = require("node-fetch");
exports.solcast = {
method: 'GET',
path: '/solcasttest',
handler: (request, h) => {
return fetch("https://linkToTheExternalApi")
.then(response => response.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err));
}
}
这篇关于如何调用外部API,然后从hapi.js Api中返回此数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!