javascriptnode.jsreactjsreportjsreport

Sending template API to JSReport from ReactJS


The Node.js client for jsreport works fine with node.js or vanilla, however, when implementing it with React I get various library errors that aren't there when the code runs directly in node. How can I use it with React?

const client = require("jsreport-client")("http://localhost:5488/");

const data = {
  template: {
    shortid: "2_Kw0BRuOm",
    recipe: "html-to-xlsx",
    data: {
      people: [{ name: "Omar rafat", age: "20", job: "Software Engineer" }],
    },
  },
};

async function render() {
  const res = await client.render(data);
  const responseBuffer = await res.body();

  const fileURL = URL.createObjectURL(responseBuffer);
  window.open(fileURL);
}


class App extends React.Component {
  myfun = () => {
    render().catch(console.error);
  };

  render() {
    return (
      <div className="App">
        <button
          onClick={() => {
            this.myfun();
          }}
        >
          Click me
        </button>
      </div>
    );
  }
}

export default App;

The part after the buffer response should be

await fs.writeFile("out.xlsx", responseBuffer);

however outputting the file into the filesystem of the server isn't what I want in the case of React, but because of the bellow error, I still don't know exactly how to handle downloading jsreport response from the browser.

The error I get after instantiating the request is

enter image description here

and the line

const res = await client.render(data);

seems to be what triggers it.


Solution

  • jsreport has a different client for browser-based applications. https://jsreport.net/learn/browser-client

    npm install jsreport-browser-client-dist
    
    jsreport.renderAsync(request).then(function(res) {
      //open in new window
      window.open(res.toDataURI())
    
      //get the content as string
      res.toString()
    
      //open download dialog
      res.download('test.pdf') 
    });