【问题标题】:Cannot console.log() function in apollo server mutation无法在阿波罗服务器突变中使用 console.log() 功能
【发布时间】:2020-02-15 14:21:38
【问题描述】:

我正在使用 nexmo 进行两步身份验证,我计划通过 graphl 突变来实现这一点,因为我有 graphql API 我无法获取 requestId 值

  Mutation: {
    signUpFirstStep: async ( parent, { number }, { models, secret }) => 
    {
     const response =  nexmo.verify.request({
        number: number,
        brand: 'Nexmo',
        code_length: '4'
      }, (err, result) => {
        const  requestId  = result.request_id
        return requestId

      });
      console.log(response);  //right here I have undefined
  }
}

我想要的只是获取 requestId 值以在突变中返回它

【问题讨论】:

  • 首先,您在其范围之外引用了response,因此是undefined。其次,您正在处理异步函数,响应是错误或结果。你登录errresult了吗?
  • @JDunken 是的,ofc,但我不知道如何让价值超出范围
  • 在函数外声明变量,如果有结果在回调中设置。
  • 请注意 GraphQL.js 依赖于 Promises,你不应该混合 Promises 和回调。如果 nexmo 库不支持 Promise,则应将回调包装在 Promise 中。请参阅常见场景 #6 here
  • @DanielRearden 感谢您的回复,它帮助了 ;)

标签: javascript async-await graphql apollo-server graphql-mutation


【解决方案1】:

nexmo.verify.request 不会返回你想要的。您需要console.log,或在(err, result) => {} 内随意处理requestId 如果您愿意,您还可以通过 res.status(200).send(result);res.status(200).send(requestId); 回复结果或 requestId。

见下文:

Mutation: {
    signUpFirstStep: async ( parent, { number }, { models, secret }) => 
    {
     nexmo.verify.request({
        number: number,
        brand: 'Nexmo',
        code_length: '4'
      }, (err, result) => {

        if(result) {  
          const  requestId  = result.request_id;
          console.log(requestId); // you should console.log or do whatever you are trying to do with the requestId here
        }
      });

  }
}

【讨论】:

  • 这是一个 GraphQL 解析器,而不是一个快速路由控制器。即使您可以通过上下文访问res 对象,您也不会使用它来返回任何数据。
猜你喜欢
  • 2019-09-15
  • 2019-10-08
  • 2019-04-02
  • 2017-03-23
  • 2021-09-09
  • 2019-02-08
  • 2020-10-18
  • 2019-02-20
  • 2021-01-24
相关资源
最近更新 更多