【问题标题】:How to Access Data By Promise chaining (Node-fetch)如何通过 Promise 链接访问数据(Node-fetch)
【发布时间】:2020-10-28 00:08:03
【问题描述】:

我想访问从第二次提取返回的用户对象(包含名称、年龄、性别等属性),但每当我这样做时,我都会得到一个意外的对象。我收到了 200 条回复,所以我不知道我错过了什么。步骤:

  1. 用户登录时获取令牌

  2. 使用令牌登录并检索用户数据。

    const fetch = require('node-fetch');
    
    
    fetch('http://34.245.86.200:9084/api/auth/login', {method:'POST',
    body: JSON.stringify({Identifier:'17123456788', Password:'bambam'}),
    headers: {'Content-type':'application/json'
    }}).then(response => { return response.json()}).then(
     data => { const header ={'Authorization': 'Bearer '+data.token}
    
     return fetch('http://34.245.86.200:9085/api/user', {
         method :'GET',
         headers: header
     })
    }).then(msg =>{
     console.log(msg.body)
    })
    

预期响应:

  {
     "title": null,
    "firstName": "Kay",
     "lastName": "Atom",
     "primaryPhoneNumber": "+1 712-345-6788",
     "fullName": "Kay Atom",
     "sex": null,
     "email": "kay@bam.com",
     "image": null,

    }

以上代码控制台登录结果:

   {
    token: 

'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJrYXlAYmFtLmNvbSIsImVtYWlsIjoia2F5QGJhbS5jb20iLCJnaXZlbl9uYW1lIjoiS2F5Iiwic2lkIjoiMzQ0MDM1ODM5NGZmNGUxNzhkMmJhNzcxNmVjYjM3YTgiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJQYXRpZW50IiwiYXV0aF90aW1lIjoiMDcvMDcvMjAyMCAxNzowOTo1MCIsImV4cCI6MTU5NDE0ODk5MCwiaXNzIjoiTGVpbGFQcm9qZWN0IiwiYXVkIjoiTGVpbGFQcm9qZWN0In0.DHuxUY77Jrsd_wBOrcZ-cmqvE8nh5I3TzpLIrRUuuhI', P>

   message: 'Successfully Logged In kay@bam.com'
      }
    



           PassThrough {
           _readableState: ReadableState {
            objectMode: false,
           highWaterMark: 16384,
           buffer: BufferList { head: [Object], tail: [Object], length: 1 
           },
    length: 372,
    pipes: [],
    flowing: null,
    ended: false,
   endEmitted: false,
    reading: true,
   sync: false,
   needReadable: true,
   emittedReadable: false,
   readableListening: false,
   resumeScheduled: false,
   errorEmitted: false,
   emitClose: true,
   autoDestroy: true,
   destroyed: false,
    errored: false,
   closed: false,
   closeEmitted: false,
   defaultEncoding: 'utf8',
   awaitDrainWriters: null,
   multiAwaitDrain: false,
   readingMore: false,
   decoder: null,
   encoding: null,
   [Symbol(kPaused)]: null
   },
   _events: [Object: null prototype] {
   prefinish: [Function: prefinish],
   unpipe: [Function: onunpipe],
   error: [ [Function: onerror], [Function (anonymous)] ],
   close: [Function: bound onceWrapper] { listener: [Function: onclose] },
   finish: [Function: bound onceWrapper] { listener: [Function: onfinish] 
     }``
   },
   _eventsCount: 5,
   _maxListeners: undefined,
   _writableState: WritableState {
   objectMode: false,
   highWaterMark: 16384,
   finalCalled: false,
   needDrain: false,
   ending: false,
   ended: false,
   finished: false,
   destroyed: false,
   decodeStrings: true,
   defaultEncoding: 'utf8',
   length: 0,
   writing: false,
   corked: 0,
   sync: false,
    bufferProcessing: false,
  onwrite: [Function: bound onwrite],
   writecb: null,
   writelen: 0,
    afterWriteTickInfo: null,
  buffered: [],
 bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: false,
closed: false
      },
     allowHalfOpen: true,
    _transformState: {
     afterTransform: [Function: bound afterTransform],
     needTransform: true,
     transforming: false,
     writecb: null,
     writechunk: null,
     writeencoding: 'buffer'
    },
    [Symbol(kCapture)]: false

【问题讨论】:

  • 您不小心创建了一个全局变量header(前面缺少const),我想知道您是否有意访问两个不同的端口(第一次是9084, 9085 第二次),但除此之外它看起来还不错。您能否添加完整的错误和(如果适用)其堆栈?你希望看到什么输出,你看到的是什么?你说“一个意想不到的物体”,但不清楚这是什么意思。谢谢。
  • @CherryDT 我刚刚编辑它以将标头定义为 const 并得到与我之前相同的响应。请参阅编辑后的问题以了解我得到的回复
  • 谢谢,但您仍然没有准确描述您所指的“意外对象”。
  • @CherryDT 消息后显示的对象是意外对象。当我在邮递员上测试 API 时,我得到了一个不同的对象(预期)

标签: javascript node.js fetch node-modules fetch-api


【解决方案1】:

response.body 指的是响应流。你可能想要response.json()response.text() 之类的东西,它们都会返回一个promise。

【讨论】:

  • 预期回复请见上文
  • @idiot,我读了你的问题,这是我试图给你一个提示来解决这个问题的尝试。您正在使用.body,它为您提供了该流对象。不要使用.body,而是使用.json()
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2020-11-28
  • 2020-04-24
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
相关资源
最近更新 更多