【问题标题】:How to authenticate using bearer token using got.js如何使用 got.js 使用不记名令牌进行身份验证
【发布时间】:2020-05-02 21:52:05
【问题描述】:

我正在尝试从 request.js 切换到 got.js。我希望看到got.js 实现与request.js 库的身份验证方式类似。但是,相反,我收到以下错误。

不再支持身份验证。替换为用户名和密码。

文档页面上没有提到bearer 令牌。

那么如何使用 got.js 使用不记名令牌验证我的请求?还是我做错了什么?

当前代码:request.js,正在运行
const request = require('request');
const module.exports = config => {
  const options = {
    auth: {
      bearer: config.secret,
    },
  };
  const result = await new Promise(( resolve, reject, ) => {
    request.get( url, options, ( error, response, body, ) => {
  ...
新代码:got.js,抛出错误
const got = require('got');

module.exports = async config => {
  const options = {
    auth: {
      bearer: config.secret,
    },
  };
  const result = await got(url, options);
  ...
}

【问题讨论】:

标签: javascript node.js request


【解决方案1】:

为我工作!!

router.get('/product', (req,res)=>{
     const dataStream =  got.stream({
      url: "http://localhost:8000/products",
      method: "GET",
    
        hooks: {
        beforeRequest: [
            options => {
                var token= 'Bearer ' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTkzODA0NjIsImV4cCI6MTYxOTM4NDA2Mn0.JoJbRpPniGuMbwULEtts7I19QxEImvarT6AoqVuNb9w'
                options.headers['Authorization'] = token;

            }
        ]
    }
     });

pipeline(dataStream, res, (err) => {
      if (err) {
          console.log(err);
          res.sendStatus(500);
      }
  });
});
 

【讨论】:

    【解决方案2】:

    如果我没记错的话,这应该可以工作

    const options = {
        headers: {
          'Authorization' : 'Bearer yourtoken'
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2017-08-16
      • 2017-07-25
      • 1970-01-01
      • 2021-04-29
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多