【问题标题】:rest-hapi standalone endpoint not returning handler resultsrest-hapi 独立端点不返回处理程序结果
【发布时间】:2019-08-12 10:00:00
【问题描述】:

如果这是一个愚蠢的问题,请原谅我,但我上一次使用 javascript 编码是在 20 年前...这几周我正在重新学习 javascript,但我不确定我是否掌握了所有内容。

我正在使用hapi和rest-hapi,想添加一些standalone endpoints,基本上是翻译this Autodesk tutorial表单快递的后端部分。

我正在使用basic rest-hapi example 主脚本,并尝试使用以下代码添加路由:

//api/forge.js
module.exports = function(server, mongoose, logger) {
  const Axios = require('axios')
  const querystring = require('querystring')
  const Boom = require('boom')

  const FORGE_CLIENT_ID = process.env.FORGE_CLIENT_ID
  const FORGE_CLIENT_SECRET = process.env.FORGE_CLIENT_SECRET
  const AUTH_URL = 'https://developer.api.autodesk.com/authentication/v1/authenticate'

  const oauthPublicHandler = async(request, h) => {
    const Log = logger.bind('User Token')
    try {
      const response = await Axios({
        method: 'POST',
        url: AUTH_URL,
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
          client_id: FORGE_CLIENT_ID,
          client_secret: FORGE_CLIENT_SECRET,
          grant_type: 'client_credentials',
          scope: 'viewables:read'
        })
      })
      Log.note('Forge access token retrieved: ' + response.data.access_token)
      return h.response(response.data).code(200)
    } catch(err) {
      if (!err.isBoom){
        Log.error(err)
        throw Boom.badImplementation(err)
      } else {
        throw err
      }
    }
  }

  server.route({
    method: 'GET',
    path: '/api/forge/oauth/public',
    options: {
      handler: oauthPublicHandler,
      tags: [ 'api' ],
      plugins: {
        'hapi-swagger': {}
      }
    }
  })
}

代码有效,我可以在 nodejs 控制台中显示 access_token,但 swagger 没有得到响应:

一开始我以为async函数不能用作handler,但我的hapi版本是17.4.0,它支持async handler。

我做错了什么?

【问题讨论】:

    标签: rest hapijs hapi-swagger


    【解决方案1】:

    事实证明这是一个简单的解决方法:我只需要在我的主脚本中指定 Hapi 服务器主机名!

    问题在于 CORS,因为 Hapi 使用我的机器名称而不是 localhost。使用

    let server = Hapi.Server({
      port: 8080,
      host: 'localhost'
    })
    

    解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      相关资源
      最近更新 更多