Как получить токен для Rest Client? - PullRequest
0 голосов
/ 27 марта 2020

Когда я авторизуюсь, он проходит без ошибок, но я не могу получить токен для дальнейших запросов (получить, опубликовать).

1002 * В результате, я должен получить такой маркер:

{ "маркер": "Знаменосец eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJyb2xlX25hbWUiOiLQkNC00LzQuNC90LjRgdGC0YDQsNGC0L7RgCIsImlhdCI6MTU4NTI5MDY5MSwiZXhwIjoxNTg1Mjk0MjkxfQ.saODDtA27NAf6hThUhvltfv6bpeieWDQ8bYxLhjq6D c"}

1007

Но я не вижу его в объекте.

Результат:

Request {
    maxAttempts: 4,
    retryDelay: 5000,
    fullResponse: true,
    attempts: 1,
    options: {
      url: 'http://localhost:3000/api/auth/login',
      method: 'POST',
      json: { username: 'admin', password: '123456' },
      maxAttempts: 5,
      retryDelay: 5000,
      fullResponse: true,
      promiseFactory: [Function: defaultPromiseFactory]
    },
    retryStrategy: [Function: HTTPError],
    delayStrategy: [Function],
    _timeout: null,
    _req: Request {
      _events: [Object: null prototype] {
        error: [Function: bound ],
        complete: [Function: bound ],
        pipe: [Function]
      },
      _eventsCount: 3,
      _maxListeners: undefined,
      method: 'POST',
      maxAttempts: 5,
      retryDelay: 5000,
      fullResponse: true,
      promiseFactory: [Function: defaultPromiseFactory],
      callback: [Function],
      readable: true,
      writable: true,
      explicitMethod: true,
      _qs: Querystring {
        request: [Circular],
        lib: [Object],
        useQuerystring: undefined,
        parseOptions: {},
        stringifyOptions: {}
      },
      _auth: Auth {
        request: [Circular],
        hasAuth: false,
        sentAuth: false,
        bearerToken: null,
        user: null,
        pass: null
      },
      _oauth: OAuth { request: [Circular], params: null },
      _multipart: Multipart {
        request: [Circular],
        boundary: 'd1a5b314-42ec-44c0-87ab-c4ebf0a28613',
        chunked: false,
        body: null
      },
      _redirect: Redirect {
        request: [Circular],
        followRedirect: true,
        followRedirects: true,
        followAllRedirects: false,
        followOriginalHttpMethod: false,
        allowRedirect: [Function],
        maxRedirects: 10,
        redirects: [],
        redirectsFollowed: 0,
        removeRefererHeader: false
      },
      _tunnel: Tunnel {
        request: [Circular],
        proxyHeaderWhiteList: [Array],
        proxyHeaderExclusiveList: []
      },
      headers: {
        host: 'localhost:3000',
        accept: 'application/json',
        'content-type': 'application/json',
        'content-length': 40
      },
      setHeader: [Function],
      hasHeader: [Function],
      getHeader: [Function],
      removeHeader: [Function],
      localAddress: undefined,
      pool: {},
      dests: [],
      __isRequestRequest: true,
      _callback: [Function: bound ] AsyncFunction,
      uri: Url {
        protocol: 'http:',
        slashes: true,
        auth: null,
        host: 'localhost:3000',
        port: '3000',
        hostname: 'localhost',
        hash: null,
        search: null,
        query: null,
        pathname: '/api/auth/login',
        path: '/api/auth/login',
        href: 'http://localhost:3000/api/auth/login'
      },
      proxy: null,
      tunnel: false,
      setHost: true,
      originalCookieHeader: undefined,
      _disableCookies: true,
      _jar: undefined,
      port: '3000',
      host: 'localhost',
      path: '/api/auth/login',
      _json: true,
      body: '{"username":"admin","password":"123456"}',
      httpModule: {
        _connectionListener: [Function: connectionListener],
        METHODS: [Array],
        STATUS_CODES: [Object],
        Agent: [Function],
        ClientRequest: [Function: ClientRequest],
        IncomingMessage: [Function: IncomingMessage],
        OutgoingMessage: [Function: OutgoingMessage],
        Server: [Function: Server],
        ServerResponse: [Function: ServerResponse],
        createServer: [Function: createServer],
        get: [Function: get],
        request: [Function: request],
        maxHeaderSize: [Getter],
        globalAgent: [Getter/Setter]
      },
      agentClass: [Function: Agent] { defaultMaxSockets: Infinity },
      agent: Agent {
        _events: [Object: null prototype],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: 'http:',
        options: [Object],
        requests: {},
        sockets: {},
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256
      }
    },
    _callback: null,
    _resolve: [Function: promiseResolve],
    _reject: [Function: promiseReject],
    _promise: Promise {
      _handler: Pending {
        consumers: undefined,
        receiver: undefined,
        handler: undefined,
        resolved: false
      }
    },
    reply: [Function: requestRetryReply]
  }

запрос:

const auth =  {
    username    : "admin",
    password : "123456"
}

var options = {
    url: `${config.url}/api/auth/login`,
    method: 'POST',
    json: auth
};
try {
    var result =  request(options);
    console.log(result)

} catch {
    console.log('[ERROR]:', err);
}

1 Ответ

0 голосов
/ 27 марта 2020

Разве вы не забыли обратный звонок? Я имею в виду:

const auth =  {
    username    : "admin",
    password : "123456"
}

var options = {
    url: `${config.url}/api/auth/login`,
    method: 'POST',
    json: auth
};

request(options, function(err, res, body) {
    if(err){
        console.log('[ERROR]:', err);
    }
    else{
        let result = JSON.parse(body);
        console.log(result);
    }
});
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...