【问题标题】:Setting Content-Type header to application/x-www-form-urlencoded using apollo-datasource-rest library使用 apollo-datasource-rest 库将 Content-Type 标头设置为 application/x-www-form-urlencoded
【发布时间】:2019-07-06 10:30:59
【问题描述】:

有人在使用apollo-datasource-rest 设置Content-Type 标头时遇到问题吗?我正在尝试为 application/x-www-form-urlencoded 编码,但我的 REST API 仍然没有看到参数:

class AuthAPI extends RESTDataSource {
  ...

  willSendRequest( request ) {
    request.headers.set( 'X-API-KEY', this.apiKey )
    request.headers.set( 'Content-Type', 'application/x-www-form-urlencoded')
    console.log( request.headers )
    console.log( request.body )
  }

  async getToken( params ) {
    return this
      .post( apiEndpoints.auth.token, params )
      .catch( err => handleError( err ))
  }
}

输出:

// console.log( request.headers )
Headers {
  [Symbol(map)]: [Object: null prototype] {
    'X-API-KEY': [ '1234567890...' ],
    'Content-Type': [ 'application/x-www-form-urlencoded' ]
  }
}

// console.log( request.body )
{
  identifier: 'my.name@domain.com',
  format: 'json',
  secret: 'P@55w0rd'
}

请求 (POST) 正文的格式似乎正确,并且标头设置正确。通过邮递员使用相同的凭据和标头返回成功的结果,但由于某种原因不能通过此库:

// response
{ success: 0,
  error:
    { status: 400,
      message: 'Missing username or password',
      code: 117
    }
}

【问题讨论】:

    标签: javascript node.js post graphql apollo


    【解决方案1】:

    可能有点晚了,但我之前也遇到过同样的问题。如果要使用application/x-www-form-urlencoded,则需要将参数作为查询字符串,例如

    class AuthAPI extends RESTDataSource {
      ...
    
      willSendRequest( request ) {
        request.headers.set( 'X-API-KEY', this.apiKey )
        console.log( request.headers )
        console.log( request.body )
      }
    
      async getToken( params ) {
        return this
          .post(
              apiEndpoints.auth.token,
              'loginId=myloginId&password=12345678',
               {
                  headers: {
                     'Content-Type': 'application/x-www-form-urlencoded',
                  },
               }
          )
          .catch( err => handleError( err ))
      }
    }
    

    不是很好,但应该可以工作

    【讨论】:

    • 谢谢。我将查询参数设置为一个对象,但无法弄清楚为什么事情不起作用。对代码解决方案的一项更正:您不需要在 willSendRequest 和 this.post 中都设置 Content-Type 标头。
    • 我认为您必须向我们展示您的代码才能帮助您。是的,谢谢你的更正!
    • 这个解决方案也适用于我。
    猜你喜欢
    • 2019-02-04
    • 2019-05-24
    • 2018-05-12
    • 2018-06-20
    • 2019-10-26
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多