10

我只是尝试使用 async/awaitrequest-promise并遇到此错误:

RequestError: Error: no auth mechanism defined
      at new RequestError (node_modules/request-promise-core/lib/errors.js:14:15)
      at Request.plumbing.callback (node_modules/request-promise-core/lib/plumbing.js:87:29)
      at Request.RP$callback [as _callback] (node_modules/request-promise-core/lib/plumbing.js:46:31)
      at self.callback (node_modules/request/request.js:188:22)
      at Auth.onRequest (node_modules/request/lib/auth.js:133:18)
      at Request.auth (node_modules/request/request.js:1360:14)
      at Context.<anonymous> (test/routes.js:37:41)
  From previous event:
      at Request.plumbing.init (node_modules/request-promise-core/lib/plumbing.js:36:28)
      at Request.RP$initInterceptor [as init] (node_modules/request-promise-core/configure/request2.js:41:27)
      at new Request (node_modules/request/request.js:130:8)
      at request (node_modules/request/index.js:54:10)
      at Context.<anonymous> (test/routes.js:37:24)

这是我最近构建的一个 API 端点,它应该在 MongoDB 中创建一个新用户。它使用 Passport 策略提供的 Basic Auth,我已经用 Postman 测试过它可以工作。我不确定为什么会抛出这个错误。

我的请求代码(使用 Mocha):

it("creates a new user", async () => {
  const options = {
    method: "POST",
    uri: `http://localhost:${process.env.PORT}/api/users`,
    headers: {
      "User-Agent": "Request-Promise",
      "Content-Type": "application/json"
    },
    body: {
      email: "test@domain.com",
      password: "password",
      firstName: "John",
      lastName: "Smith"
    },
    json: true
  };
  const resp = await request(options).auth(APP_ID, SIGNATURE, false);
  expect(resp).to.be.an("object");
});

编辑:我可能还应该补充一点,我正在使用节点 8.2.1 和 npm 5.3.0。

4

3 回答 3

7

通过更改为我解决了:

auth: { Bearer: token }

至:

auth: { bearer: token }

请注意“承载”的大小写差异。

于 2018-09-30T01:33:08.137 回答
1

这通常是由于未提供合适的凭据造成的。可以在此处找到引发错误的代码。您是否已验证APP_ID并且SIGNATURE不在undefined您的测试中?

于 2017-09-15T12:48:46.917 回答
0

这个解决方案对我有用。我需要将令牌放在标题中:

var rp = require('request-promise');

var uri = 'uri_for_my_post_request';
var token = 'access_token';
var body =  {
    title: 'My Title',
    content : 'My content'
}; 

var sendPost = async(my_uri,my_token,my_body)=>{
    var options = {
    method: 'POST',
    headers:{
        Authorization: ' Bearer ' + my_token           
   },
    uri: my_uri,
    body: my_body,
    json: true
};

const response = await rp(options);
console.log(response);
}

sendPost(uri,token,body);
于 2020-02-02T11:55:11.907 回答