如何通过在标头中传递JWT令牌的node.js进行GET请求

时间:2020-06-12 17:57:02

标签: node.js authentication get jwt

我一直在尝试对在本地端口4000上运行的服务器发出GET请求。

我生成一个JWT令牌,并按如下所述将其传递到标头中

var request = require('request');
var options = {
  'method': 'GET',
  'url': 'localhost:4000',
  'headers': {
    'JWT': '<JWT PASTED HERE>',
    'Content-Type': 'application/json'
  }
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

但是我不断得到


{"errors":[{"title":"invalid_request","id":"Requesting stuff","meta":{"server-time":1591980353},"errorCode":"bad-request","status":400,"detail":"This JWT has invalid path parameter"}],"error_description":"This JWT has invalid path parameter","error":"invalid_request"}

我的JWT已正确创建,我在https://jwt.io/中对其进行了验证

是因为在node.js中弃用了“请求”模块吗?

还有其他方法可以实现以下目标吗?

1 个答案:

答案 0 :(得分:1)

尝试这个

import _ from 'lodash'

const = deepReplaceRecursive(old, new, obj) = {
  const new = _.clone(obj);

  _.each(object, (val, key) => {
    if (val === old) {
      // replace val if it's equal to the old value
      newObj[key] = new;
    } else if (typeof(val) === 'object' || typeof(val) === 'array') {
      // if val has nested values, make recursive call
      newObj[key] = deepReplaceRecursive(old, new, val);
    }
  });

  return newObj;
}

const object = { ... }
const newObject = deepReplaceRecursive("name", "replaceName", object)

var request = require('request');
var options = {
  'method': 'GET',
  'url': 'localhost:4000',
  'headers': {
    'Authorization': 'Bearer <JWT PASTED HERE>',
    'Content-Type': 'application/json'
  }
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

承载者或JWT取决于后端中的定义