【问题标题】:How do i call third party API data via fastify?如何通过 fastify 调用第三方 API 数据?
【发布时间】:2021-04-19 20:29:56
【问题描述】:

我有一个小型节点服务器,我使用框架 fastify。

在我的一条路线中,我想从第三方 API 获取数据。

我尝试了以下sn-p:

fastify.route({
    method: 'GET',
    url: 'https://demo.api.com/api/v2/project/',
    handler: async function ({ params, body}, reply) {
        if (!body) return reply.send({ sucess: false })

        console.log('testing')
        console.log(body)

        return reply.send({ sucess: true })
    }
})

很遗憾,我无法通过 get 调用 URL,因为 GET url 只能以 '/' 开头。

如何通过 fastify 调用第三方 api?我需要延期吗?

【问题讨论】:

    标签: api fastify


    【解决方案1】:

    如果您需要定义代理另一台服务器的路由(如http://localhost:3000/),您需要使用fastify-http-proxy

    或者,如果您需要调用另一个端点并管理响应,可以使用 fastify.inject() 实用程序,但它是为测试而设计的。

    无论如何,我认为最好的方法是使用一些 HTTP 客户端,例如 got

    const got = require('got') // npm install got
    
    fastify.get('/my-endpoint', async function (request, reply) {
      const response = await got('sindresorhus.com')
      console.log(response.body)
      // DO SOMETHING WITH BODY
      return { sucess: true }
    })
    

    【讨论】:

    • { "statusCode": 500, "error": "Internal Server Error", "message": "got is not defined" }
    • 我收到消息:“未定义”。
    • npm install got
    • exports.authentication = async (req, reply) => { try { const response = await got({ method: 'POST', url: https://url, headers: { 'Authorization': '承载 2HdfkjdfRg.XlgsfdkafjdfjfiWaTdnpg-OALdkfjfd' } }) 返回 response.body; } 捕捉(错误){ 抛出繁荣.boomify(错误)} }
    • 先生,我正在这样做,这样对吗?在我得到 npm 之后,我仍然收到同样的错误
    【解决方案2】:

    使用 fastify 挂钩将您的 http 请求代理到另一台服务器。

    这是 fastify-http-proxy 中的示例

    server.register(require('fastify-http-proxy'), {
      upstream: 'http://my-api.example.com',
      prefix: '/api', // optional
      http2: false // optional
    })
    

    https://github.com/fastify/fastify-http-proxy/blob/master/example.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 2020-01-03
      • 2017-09-29
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多