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()