简体   繁体   中英

Proxy API request through Express return pending Promise instead of response

I am currently trying to work with the Atlassian Jira rest API. In order to not get a CORS error I go through the recommended route of not sending the request from the browser but proxy it through my express server.

Now as I am doing this, all I receive back in the app is a pending promise. I assume that I have not correctly resolved it at one point but I cant figure out where.

API Handler sending the request to the proxy:

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

Jira Proxy Endpoint on the Express Server

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 & handle Error Methods:

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

Goal: Send the request of sending a request to the proxy and return the resonse of the proxy as the return of the initial "testConction" method.

Error: No errors thrown, but the response received in the Browser is a pending promise.

Change to the Jira Proxy router fixed it. Thanks to @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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM