Estoy tratando de tomar texto de un campo de entrada HTML y enviarlo a través de una solicitud POST a un script de python para su procesamiento (estoy usando un proceso secundario).
En este momento, solo estoy enviando los datos procesados a la respuesta y sobrescribiendo el index.html, pero me gustaría escribir la salida del script de python en un campo de texto debajo del campo de entrada en el mismo punto final ("/") .
¿Hay alguna manera de hacer esto sin tener que volver a renderizar todo el HTML con solo el nuevo texto agregado?
servidor.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}!`));índice.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 realmente puede hacer cualquier cosa aquí:
import sys sentence = sys.argv[1] print(sentence , " this is stuff added to the sentence") sys.stdout.flush()índice.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 (eliminé bodyParser y agregué 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}!`));