M dunbavan
M dunbavan

Reputation: 1167

How can I return JSON data in body in express router.get?

I am trying to use express to create an endpoint so I can retrieve data from an API and return the JSON data in the body.

We are getting data from a rest API that returns an array of JSON data. What I would like is to use express router.get to display the JSON formatted on the front-end so I can then access the endpoint and get the data. Here is what I have so far:

"use strict";
const express = require("express");
const path = require("path");
const serverless = require("serverless-http");
const app = express();
const bodyParser = require("body-parser");
const fetch = require("node-fetch");
var async = require("express-async-await");

const router = express.Router();
router.get("/", async function(req, res, next) {
  var requestOptions = {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization:
        "Basic *********",
      "Access-Control-Allow-Origin": "*"
    },
    redirect: "follow"
  };

  async function getApi() {
    try {
      const response = fetch(
        "http://www.reed.co.uk/api/1.0/search?employerId=*******",
        requestOptions
      )
        .then(res => {
          return res.json();
        })
        .then(json => {
          return json;
        });
      return response;
    } catch (error) {
      console.log(error);
    }
  }

  const ooIprocessData = async () => {
    const data = await getApi();
    const ooiResponseData = await data;
    return ooiResponseData;
  };
  ooIprocessData();
  res.end;
});

The below code returns the data in the node response when we access the router but it shows <Pending> and I need to resolve it on the front-end.

Can anyone point me in the right place for this to work?

Upvotes: 0

Views: 1707

Answers (2)

user14520680
user14520680

Reputation:

Response has a function called json to send back JSON data. You can also optionally use Response.prototype.status to provide metadata about whether it worked or not. For example,

res.status(200).json({status: 1, msg: 'Fetched successfully'});

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14904

You have some unnessecary steps here. Also you could move your function outside of your router function.

"use strict";
const express = require("express");
const path = require("path");
const serverless = require("serverless-http");
const app = express();
const bodyParser = require("body-parser");
const fetch = require("node-fetch");
var async = require("express-async-await");

const router = express.Router();

router.get("/", async function(req, res) {
  var requestOptions = {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization: "Basic *********",
      "Access-Control-Allow-Origin": "*"
    },
    redirect: "follow"
  };
  try {
    let result = await getApi(requestOptions);
    res.status(200).json(result);
  } catch (err) {
    return res.status(500).json(err);
  }
});

function getApi(requestOptions) {
  return fetch(
    "http://www.reed.co.uk/api/1.0/search?employerId=*******",
    requestOptions
  ).then(res => {
    return res.json();
  });
}

Your problem was also that getApi returns an promise that resolves to undefined because you try to return outside of the promise chain

Use async / await where its useful. Not where it could maybe work

Upvotes: 1

Related Questions