如何在 express router get 请求中使用 node-fetch 中的 fetch

How to use fetch from node-fetch inside an express router get request

我正在使用 node-fetch 从 express router get 请求中的 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(响应),我得到(从 github 用户 rmosolgo 搜索回购,例如:

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
  }
}

如果您想从响应中 get/extract JSON,您需要对响应执行异步 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);

希望对您有所帮助!

你可以这样试试。一切正常

// async/await to get a synchronously
async functionName() {

    const items = await fetch('/url')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {
      return responseJson.myString
    })

}

// async/await 
const body = {a: 1};

const response = await fetch('https://httpbin.org/post', {
    method: 'post',
    body: JSON.stringify(body),
    headers: {'Content-Type': 'application/json'}
});
const data = await response.json();

console.log(data)

ttps://www.npmjs.com/package/node-fetch