使用 apollo-datasource-rest 库将 Content-Type 标头设置为 application/x-www-form-urlencoded

Mar*_*k D 4 javascript post node.js apollo graphql

有没有人在Content-Type使用设置标题时遇到问题apollo-datasource-rest?我正在尝试编码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 ))
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

// 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'
}
Run Code Online (Sandbox Code Playgroud)

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

// response
{ success: 0,
  error:
    { status: 400,
      message: 'Missing username or password',
      code: 117
    }
}
Run Code Online (Sandbox Code Playgroud)

Ewe*_*Min 6

可能有点晚了,但我以前也遇到过同样的问题。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 ))
  }
}
Run Code Online (Sandbox Code Playgroud)

不是很好,但它应该有效