如何在快速路由器获取请求中使用从节点获取中获取

时间:2021-07-27 22:23:22

标签: javascript express mern node-fetch express-router

我正在使用 node-fetch 从快速路由器获取请求中的 github(用户存储库)获取外部资源,如下所示。

import fetch from 'node-fetch

router.get('/github/:username', async (req, res) => {
  try {
    const uri = `http://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${process.env.GITHUB_CLIENT_ID}&client_secret=${process.env.GITHUB_CLIENT_SECRET}`;

    const response = await fetch(uri, {
      method: 'GET',
      mode: 'cors',
      headers: { 'Content-Type': 'application/json' }
    });

    return res.json(response);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('server error');
  }
});

但是当我到达这条路线时,我在邮递员那里得到了以下回复:

{
    "size": 0,
    "timeout": 0
}

有人知道我做错了什么吗?

编辑:

如果我从 fetch 获取 console.log(response),我得到(例如从 github 用户 rmosolgo 搜索 repos:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 5b 7b 22 69 64 22 3a 33 37 33 31 38 30 35 32 32 2c 22 6e 6f 64 65 5f 69 64 22 3a 22 4d 44 45 77 4f 6c 4a 6c 63 47 39 7a 61 58 52 76 63 6e 6b 7a 4e 7a ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _maxOutputLength: 4294967295,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false,
      [Symbol(kTransformState)]: [Object],
      [Symbol(kError)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://api.github.com/users/rmosolgo/repos?per_page=5&sort=created:asc&client_id=Iv1.cafc8d8f7e1b91ac&client_secret=824bedd0eb406f92a3380d8043c273655cdc1f99',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 1
  }
}

2 个答案:

答案 0 :(得分:0)

如果您想从响应中获取/提取 JSON,则需要对响应执行 async json()res.json 会自动为您执行此操作。这类似于浏览器中的 fetch

const response = await fetch(uri, {
  method: 'GET',
  mode: 'cors',
  headers: { 'Content-Type': 'application/json' }
}).then(res => res.json());

return res.json(response);

或:

const response = await fetch(uri, {
  method: 'GET',
  mode: 'cors',
  headers: { 'Content-Type': 'application/json' }
})

const data = await response.json();

return res.json(data);

希望有帮助!

答案 1 :(得分:0)

使用这种方式:

const fetch = require('node-fetch'); fetch('https://google.com').then(res => res.text()).then(text =>console.log(text))