0

I am trying to take text from an HTML input field and send it via POST-request to a python script for processing (I am using child process).

Right now, I am just sending the processed data to the response and overwriting the index.html, but I would like to just write the output of the python script into a text field under the input field in the same endpoint ("/").

Is there a way of doing this without having to re-render the entire HTML with just the new text added to it?

server.js:

const express = require("express");
const { spawn } = require("child_process");
const path = require("path");
const bodyParser = require("body-parser");

const router = express()

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({extended:true}));


app.get("/", (req, res) => {
    res.sendFile(path.join( __dirname+'/index.html'));
});

app.post("/", (req, res) => {

    // This is where the text field data is parsed into the python script
    const python = spawn("python", ["script.py", req.body.sentence]);
    

    python.stdout.on("data", function (data) {
        processed_data = data.toString();
    });
    python.stderr.on("data", data => {
        console.error(`stderr: ${data}`);
    })
    python.on("exit", (code) => {
        
        // Something else here possibly?
        res.send(processed_data);

    });
})

app.listen(port, () => console.log(`App listening on port ${port}!`));

index.html:

<form method="POST" action="/">
    <fieldset>
        <label>Write a sentence:</label>
        <input type="text" id="sentence" name="sentence" required>
        <br><br>
        <button type ="submit">Run</button>
        <br><br>
        <textfield id=output_field><textfield>
    </fieldset>
</form>

script.py can really do anything here:

import sys

sentence = sys.argv[1]
print(sentence , " this is stuff added to the sentence")

sys.stdout.flush()
Python Dong
  • 85
  • 1
  • 5

1 Answers1

0

index.html

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
 
        <fieldset>
            <label>Write a sentence:</label>
            <input type="text" id="sentence" name="sentence" required>
            <br><br>
            <button id='buttonFetch'>Run</button> 
            <br><br>
            <textfield id="output_field"><textfield>
        </fieldset>
 
<script>
const button = document.querySelector("#buttonFetch")
button.addEventListener("click", () => {

 const sentence = document.querySelector("#sentence").value
  fetch("http://localhost:3000/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
        sentence
    }),
  })
    .then(res => res.text())
    .then(data => {
        console.log(data)
        const output_field = document.querySelector("#output_field")
        output_field.textContent = data
    })
    .catch(e => {
      console.error(e.error)
    })
})
</script>
</body>
</html>

server.js (I removed bodyParser and add express.json())

'use strict'

const express = require("express");
const { spawn } = require("child_process");
const path = require("path");
//const bodyParser = require("body-parser");

const router = express()

const app = express();
const port = 3000;

app.use(express.json())

//app.use(bodyParser.urlencoded({extended:true}));

app.get("/", (req, res) => {
    res.sendFile(path.join( __dirname+'/index.html'));
});

app.post("/", (req, res) => {
    console.log(`req.body.sentence: ${req.body.sentence}`)

    // This is where the text field data is parsed into the python script
    const python = spawn("python", ["script.py", req.body.sentence]);
    
    let processed_data = ''

    python.stdout.on("data", function (data) {
         processed_data = data.toString();
    });
    python.stderr.on("data", data => {
        console.error(`stderr: ${data}`);
    })
    python.on("exit", (code) => {
        // Something else here possibly?
        console.log(processed_data)
        res.send(processed_data);
    });
})

app.listen(port, () => console.log(`App listening on port ${port}!`));
ManuelMB
  • 1,254
  • 2
  • 8
  • 16