如何在 node.js 中使用需要 username/password 身份验证的 REST api

How to consume a REST api that needs username/password authentication in node.js

我想在 node.js 中使用需要 username/password 身份验证的 REST api。消耗api的代码如下:

var request = require('request');

var url = 'http://localhost:3000/api/v1/login/'

request.get(url,{'auth': {'user': 'test35','pass': 'mypassword','sendImmediately': false}},function(err, httpResponse, body) {
  if (err) {
    return console.error('post failed:', err);
  }

  console.log('Post successful!  Server responded with:', body);
});

使用上面的代码,我得到的错误是:

{
  "status": "error",
  "message": "API endpoint does not exist"
}

api是用meteor restivus写的,可以在下面问题的

中看到

在API中,当我删除api的authRequired: true时,即删除

{
        routeOptions: {
            authRequired: true
        }
  }

并在使用 API 上面的 的代码中,将 url 从

更改为

'http://localhost:3000/api/v1/login/

至:

http://localhost:3000/api/v1/articles/

和运行"node accessRESTapi.js",我可以使用 REST api!我无法正确执行的是 "authRequired: true" 按上述设置时的身份验证!请帮助

编辑:根据评论中的信息更新

登录获取token和后续请求的请求风格大不相同:

待登录

docs 指定登录操作必须通过对 /api/login/POST 请求和包含 username 或 [=16] 的 body 来完成=] 和 password 作为 url-encoded 参数

var request = require('request');

var url = 'http://localhost:3000/api/v1/login/'
var user = 'test35';
var pass = 'mypassword';

// Save these for future requests
var userId;
var authToken;

// Use POST instead of GET
request.post(
  {
    uri: url,
    // I'm using form because it matches the urlEncoding behaviour expected by `restivus`
    form: { username: user, password: pass }
  },
  function(err, httpResponse, body) {
    if (err) {
      return console.error('post failed:', err);
    }
    var json = JSON.parse(body);
    authToken = json.data.authToken;
    userId = json.data.userId;
    console.log('Post successful!  Server responded with:', body);
  }
);

对于未来的请求

现在您需要使用之前保存的 userIdauthToken

设置正确的 headers

According to the docs,这意味着所有后续请求 X-User-IdX-Auth-Token headers

var request = require('request');

var url = 'http://localhost:3000/api/v1/articles/'

request.get({
  uri: url, 
  headers: {
    'X-User-Id': userId,
    'X-Auth-Token': authToken
  }
}, function(err, httpResponse, body) {
  if (err) {
    return console.error('get failed:', err);
  }

  console.log('Get successful!  Server responded with:', body);
});

放在一起:

我们想确保在提出任何进一步请求之前获得 authToken

这意味着在第一个函数的回调中发出第二个请求,如下所示:

var request = require('request');

var url = 'http://localhost:3000/api/v1/login/';
var user = 'test35';
var pass = 'mypassword';

// Save these for future requests
var userId;
var authToken;

// Use POST instead of GET
request.post(
  {
    uri: url,
    // I'm using form because it matches the urlEncoding behaviour expected by `restivus`
    form: { username: user, password: pass }
  },
  function(err, httpResponse, body) {
    if (err) {
      return console.error('post failed:', err);
    }
    var json = JSON.parse(body);
    authToken = json.data.authToken;
    userId = json.data.userId;
    console.log('Post successful!  Server responded with:', body);

    // And now we make the second request
    // Welcome to callback hell
    var articlesUrl = 'http://localhost:3000/api/v1/articles/';

    request.get({
      uri: articlesUrl, 
      headers: {
        'X-User-Id': userId,
        'X-Auth-Token': authToken
      }
    }, function(err, httpResponse, body) {
      if (err) {
        return console.error('post failed:', err);
      }

      console.log('Get successful!  Server responded with:', body);
    });
  }
);