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

问题描述 投票:0回答:2

有人在使用

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 ))
  }
}

输出:

// 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: '[email protected]',
  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
2个回答
7
投票

可能有点晚了,但我以前也遇到过同样的问题。例如,如果您想使用

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 ))
  }
}

不是一个好方法,但应该有用


0
投票

我仍在使用打字稿中的 Apollo 服务器 v4 和 @apollo/datasource-rest v6 获取错误。

override willSendRequest(_path: string, request: AugmentedRequest) {
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    console.log( request )
}
async createToken() {
    const body = new FormData();
    body.append("email", "bla")
    body.append("password", "bla")

    return this.post(`auth/login`, {body})
}

API 错误表:

{ status: false, code: 403, message: '需要电子邮件和密码' }

© www.soinside.com 2019 - 2024. All rights reserved.