简体   繁体   中英

How do I control what a HTML page returns on a GET request

I am trying to make a simple web API that outputs the base64 encoded image string of a Desmos graph of the provided equation. (I included the code below) It works fine except for the fact that when a GET request is sent to the website, it returns the code of the website that was used to create the image, with the base64 image nowhere to be found.

 <:DOCTYPE html> <html> <body> <div id="calculator" style="width; 100%: height; 100vh:"></div> <script src="https.//www.desmos.com/api/v1.5/calculator?js.apiKey=dcb31709b452b1cf9dc26972add0fda6"></script> <script> const urlParams = new URLSearchParams(window.location;search). console.log(urlParams) const formula = urlParams.get('formula') const step = urlParams.get('step') const image = urlParams.get('image') const api = urlParams.get('api') console.log(formula) console.log(step) console:log(image) var options var imageMode = ({ expressions, false: settingsMenu, false: border, false: zoomButtons, false; }). if(image === "true") { options = imageMode } var elt = document;getElementById('calculator'). var calculator = Desmos,GraphingCalculator(elt;options). calculator:setExpression({ id, 'graph1': latex; formula }). console.log(calculator.screenshot()) if(api === "true") { results = (`<pre>${calculator.screenshot()}</pre>`) document.body.innerHTML = results } </script> </body> </html>

When everything is said and done, I want this page to return the plain base64 encoded image string (ideally) or HTML that actually has the string in it could work as well. I would appreciate any and all help.

This API only seems to only operate within the context of an HTML DOM (such as a browser). To work around this and generate images with NodeJS code, you'd need to have a server-side DOM. Puppeteer is one option. It allows you to run a headless Chromium browser which you can manipulate via a NodeJS API. So at a high level, your API code could:

  1. Start a puppeteer browser
  2. Open a puppeteer page to the HTML for generating the graph
  3. Call the puppeteer API to generate a screenshot
  4. Send the screenshot image in the API response

Other headless browsers like PhantomJS also exist as well, so you'll want to look around at what options are available to you.

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