NodeJS从请求切换到axios:凭证未通过

时间:2020-09-21 09:45:17

标签: node.js request axios

到目前为止,我一直在使用现在不推荐使用的request-promise。我选择axios作为接班人,并且修改了代码,但不幸的是,我一直收到错误401“未授权”的消息。好像axios没有传递给定的身份验证信息。我的旧源代码如下:

let options = {
  method: 'GET',
  uri: 'https://example.com/bla',
  auth: {
    user: 'USER',
    pass: 'PASSWORD',
    sendImmediately: true
  },
  headers: {
    'X-CSRF-Token': 'Fetch'
  },
  resolveWithFullResponse: true
};
let rpWithDefaults = rp.defaults({
  rejectUnauthorized: false,
  jar: true
});
let response = await rpWithDefaults(options);

修改后的代码段如下所示:

const axios = require('axios').default;
const https = require('https');
const response = await axios({
    method: 'GET',
    url: 'https://example.com/bla',
    headers: {
      'X-CSRF-Token': 'Fetch'
    },
    httpsAgent: new https.Agent({  
      rejectUnauthorized: false,
      auth: {
        user: 'USER',
        pass: 'PASSWORD'
      }
    }),
    resolveWithFullResponse: true
  });

我在做什么错了?

谢谢

2 个答案:

答案 0 :(得分:1)

Axios文档说您需要通过这种方式。

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
 

那么您是否尝试将密钥从userpass更改为usernamepassword

const axios = require('axios').default;
const https = require('https');
const response = await axios({
    method: 'GET',
    url: 'https://example.com/bla',
    headers: {
      'X-CSRF-Token': 'Fetch'
    },
    auth: {
       username: '<user-name>',
       password: '<password>'
    },
    resolveWithFullResponse: true
  });

答案 1 :(得分:0)

我以前没有使用过var a = moment.tz("2020-12-12T12:00:00.0000Z", "Asia/Taipei"); a.format(); // 2020-12-12T12:55:00+08:00 参数,但是我认为在Axios中进行https调用不是必需的。以下内容对您有用吗?

httpsAgent

可能相关:reactjs make https (not http) requests with axios