【问题标题】:Proxy API request through Express return pending Promise instead of response通过 Express 的代理 API 请求返回待处理的 Promise 而不是响应
【发布时间】:2020-05-04 00:11:13
【问题描述】:

我目前正在尝试使用 Atlassian Jira REST API。为了不出现 CORS 错误,我采用了不从浏览器发送请求而是通过我的快速服务器代理它的推荐路线。

现在,当我这样做时,我在应用程序中收到的只是一个未决的承诺。我假设我有一次没有正确解决它,但我不知道在哪里。

API Handler 向代理发送请求:

const baseURL = `${apiConfig}/jiraproxy`;

export const testConnection = integration => {
  return fetch(`${baseURL}/get`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(integration)
  })
    .then(handleResponse)
    .catch(handleError);
};

Express 服务器上的 Jira 代理端点

const baseURL = `rest/api/3/dashboard`;

router.post("/get", (req, res) => {
  fetch(req.body.link + baseURL, {
    method: "GET",
    headers: { Accept: "application/json" },
    auth: {
      username: req.body.credentials.username,
      password: req.body.credentials.token
    }
  })
    .then(handleResponse)
    .catch(handleError);
});

handleResponse & 处理错误方法:

async function handleResponse(response) {
  if (response.ok) {
    return response.json();
  }
  if (response.status === 400) {
    const error = await response.text();
    throw new Error(error);
  }
  throw new Error("Network response was not ok.");
}

function handleError(error) {
  // eslint-disable-next-line no-console
  console.error(`API call failed. ${error}`);
  throw error;
}

目标: 向代理发送发送请求的请求,并将代理的响应作为初始“testConction”方法的返回返回。

错误: 没有抛出错误,但在浏览器中收到的响应是待处理的承诺。

【问题讨论】:

  • 这怎么可能奏效?您的 router.post() 永远不会向客户端发送任何类型的响应。 router.post() 处理程序中没有 res.send()res.json()
  • 另外,你知道handleResponse()async 吗?这意味着它总是返回一个承诺。因此,您试图从中得到的任何结果都将是它返回的承诺的已解决值。你根本没有用handleResponse() 展示你想要完成的事情。所有,它似乎只是检查错误并调用response.json(),但你永远不会在你的router.post()处理程序中对这个结果做任何事情。
  • 好吧,我现在应该睡觉了——谢谢你的问题!
  • 为了清楚起见,我自己回答了这个问题,

标签: node.js rest express proxy node-fetch


【解决方案1】:

更改为 Jira 代理路由器修复了它。感谢@jfriend00。

router.post("/get", (req, res) => {
  return fetch(req.body.link + baseURL, {
    method: "GET",
    headers: { Accept: "application/json" },
    auth: {
      username: req.body.credentials.username,
      password: req.body.credentials.token
    }
  })
     // This is the part that changed
    .then(response => handleResponse(response))
    .then(jiraResponse => res.status(200).json(jiraResponse))
    .catch(handleError);
});

【讨论】:

  • 仅供参考,您可以将此.then(jiraResponse => res.status(200).json(jiraResponse)) 更改为.then(res.json.bind(res))。无需将状态设置为 200(这是默认值),您可以让 .then() 处理程序为您调用 res.json()
  • 另外,如果你真的只是想代理实际的响应,你可以使用类似request() 库和.pipe() 的响应返回。您甚至不必自己解析响应,只需将其传递即可。有关示例,请参见 stackoverflow.com/questions/20351637/…
猜你喜欢
  • 2020-01-21
  • 1970-01-01
  • 2021-01-17
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多