为什么我通过此POST请求获取invalid_client?

时间:2018-06-14 17:33:03

标签: javascript post npm http-post httprequest

我正在尝试与具有以下规范的外部API进行通信:

Host: name.of.host
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache

使用request的{​​{1}}模块,我正在构建POST请求,如下所示:

npm

标题和正文对象的设置如下:

function post2(uri, headerObj, bodyObj, bodyStr) {
  console.log("Posting to " + uri + " . . .");

  var options = {
    uri: uri,
    form: bodyObj,
    qs: bodyObj,
    method: 'POST',
    json: false,
    headers: headerObj
  };

  request(options, function(error, response) {
    console.log(JSON.stringify(response));
    console.log(error, response.body);
    return;
  });
}

我仔细检查了var headerObj = { 'Host': 'name.of.host', 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'no-cache' }; var bodyObj = { 'client-id': 'GUID', 'grant_type': 'refresh_token', 'refresh_token': 'alpha-numeric data that also includes / = and + chars' }; client-id元素是否包含正确的数据。我也在Postman上用相同的上述内容测试了这个请求,它没有任何问题。尽管如此,我仍然从API中收到以下错误:

refresh_token

我参考了here关于null '{"error":"invalid_client"}' npm模块的文档,并按照请求(选项,回调),因为request 确实如此似乎不允许您输入任何标题。我做错了什么?

- 编辑 -

所以现在我尝试使用XMLHttpRequest代替并设置相同的标题。首先我收到request.post错误,因此我删除了主机标头并再次尝试。这一次我没有错误但是没有在cmd上打印响应(我正在使用节点部署)。

这是我的代码:

Refused to set unsafe header "Host"

我不明白什么可能是错的。我没有看到浏览器上的传出请求,但是由于我可以从节点cmd看到日志,所以肯定会尝试。

1 个答案:

答案 0 :(得分:0)

问题很简单:

var bodyObj = {
  'client-id': 'GUID', // note how the key contains a dash 
  'grant_type': 'refresh_token',
  'refresh_token': 'alpha-numeric data'
};

另一方面,它起作用:

var bodyObj = {
      'client_id': 'GUID', // switch to underscore 
      'grant_type': 'refresh_token',
      'refresh_token': 'alpha-numeric data'
    };

语法错误最严重。

相关问题