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

问题描述 投票:0回答:2

我正在使用

node-fetch
在 Express 路由器获取请求中从 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 搜索存储库,例如:

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
  }
}
javascript express mern node-fetch express-router
2个回答
3
投票

如果要从响应中获取/提取 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);

希望有帮助!


0
投票

你可以试试这个方法。工作正常

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

© www.soinside.com 2019 - 2024. All rights reserved.