简体   繁体   English

如何在 express router.get 中返回正文中的 json 数据?

[英]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.我正在尝试使用 express 创建一个端点,以便我可以从 api 检索数据并在正文中返回 json 数据。

We are getting data from a rest api that returns an array of json data.我们正在从返回 json 数据数组的 rest api 获取数据。 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.我想要的是使用 express router.get 来显示在前端格式化的 json,这样我就可以访问端点并获取数据。 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 and I need to resolve it on the front-end.下面的代码在我们访问路由器时返回节点响应中的数据,但它显示,我需要在前端解析它。

Can anyone point me in the right place for this to work?任何人都可以指出我在正确的地方工作吗?

Thanks,谢谢,

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您的问题还在于getApi返回了一个解析为undefined的承诺,因为您尝试在承诺链之外返回

Use async / await where its useful.在有用的地方使用async / await Not where it could maybe work不是它可能工作的地方

Response has a function called json to send back JSON data. Response有一个名为json的函数来发回 JSON 数据。 You can also optionally use Response.prototype.status to provide metadata about whether it worked or not.您还可以选择使用Response.prototype.status来提供有关它是否有效的元数据。 For example,例如,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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