Home > front end >  React direct to external NodeJS route and display data from processed body
React direct to external NodeJS route and display data from processed body

Time:09-10

i have this fetch request which send some body data to http://localhost:8000/report and then redirects to the same route on server to display data after processing :

  const handleGo = async () => {
    const employee = {
      name: name.current.value,
      month: month.current.value,
      year: year.current.value,
    };
    await fetch("http://localhost:8000/report", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(employee),
    });
    window.location.replace("http://localhost:8000/report");
  };

index.json server

const client = require("@jsreport/nodejs-client")("http://localhost:8001");

app.post("/report", (req, res, next) => {
  employee.getEmpReport(req, res, next, client);
});

function getEmpReport

const getEmpReport = async (req, res, next, client) => {
  const { name, month, year } = req.body; /// processing body data coming from react client

  Employee.aggregate([
     // doing some MongoDB join with conditions and returning results

  ]).exec(function (err, employee) {

    const dataObject = {
         /// setting some data from returned employee
    };
    client
      .render({
        template: { name: "/salary/salarySlipTemplate" },
        data: dataObject,
        options: { reports: { save: true } },
      })
      .then((response) => response.pipe(res))
      .catch(next);
  });
};

i want this route to process data and then display data after processing, but when window.location.replace("http://localhost:8000/report"); redirects to the route it says cannot get /report

i think i need a get route but then how can i recieve body data ? i want to be able to recieve the data from client and display it at the same time, how can i do that ?

CodePudding user response:

i should send request from client to jsreport client and send data directly, server should only return the filtered employee:

import jsreport from "@jsreport/browser-client";
jsreport.serverUrl = "http://localhost:8001";

  const handleGo = async () => {
    const employee = {
      name: name.current.value,
      month: month.current.value,
      year: year.current.value,
    };

    const response = await fetch("http://localhost:8000/report", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(employee),
    });

    const data = await response.json();

    const report = await jsreport.render({
      template: {
        name: "/salary/salarySlipTemplate",
      },
      data: data,
    });
    report.openInWindow({ title: "salary slip" });
  };

  • Related