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

5

有人在使用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)正文格式正确,标头也设置正确。使用相同的凭据和标头通过Postman发送请求可以返回成功结果,但是通过这个库却不行。

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

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

虽然不太好,但应该能用


谢谢。我将我的查询参数设置为对象,但是无法弄清楚为什么事情不起作用。对于您的代码解决方案,有一个更正:您不需要在willSendRequest和this.post中都设置Content-Type标头。 - doubledherin
我认为你必须展示你的代码,这样我们才能帮助你。是的,谢谢你的纠正! - Ewe Tek Min
这个解决方案对我也有效。 - sasitha999

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接