简体   繁体   English

在 cheerio 上获取所需输入 (html) 的字符串值

[英]Getting string value of required input (html) on cheerio

I'm trying to do a notify function in my website.我正在尝试在我的网站上发送通知 function。 The button his on HTML (client side) and on press calls a node.js function to execute a python script that sends an e-mail to myself (tested and working).他在 HTML(客户端)和按下时的按钮调用 node.js function 来执行 python 脚本,该脚本向我自己发送电子邮件(经过测试和工作)。

This is my code on the client side (index.html)这是我在客户端的代码(index.html)

<body>
    ...
    <div class="form-popup" id="myForm">
      <form class="form-container" name="form-owner">
        <h1>Notify Owner</h1>
        <label><b>Name</b></label>
        <input id="name" style="width:90%" type="text" placeholder="Enter your name" required>
        <label><b>Message</b></label>
        <input id="context" style="width:90%" type="text" placeholder="Enter Reason" required>
        <button type="submit" class="btn" onclick="notifyOwner()">Submit</button>
        <button type="button" class="btn cancel" onclick="closeForm()">Close</button>
      </form>
    </div>
  </div>
...

The code on the server side (app.js)服务器端的代码(app.js)

const express = require('express');
const child_process = require('child_process')
const app = express()
const cheerio = require('cheerio');
const port = 80
'use strict';
var request = require('request');

...

app.post("/api/notify", async (req, res) => {
  try{
    const $ = cheerio.load('<input id="name" style="width:90%" type="text" placeholder="Enter your name" required>');
    var subject = $('[id=name]').text();
    var body = "ok";
    child_process.execSync('python3 sendEmail.py ' + subject + " " + body);
  }catch(error){
    console.error(error);
  }
});

The varialbe 'subject' turns out as null and the script is not runned because that argument is missing变量“主题”结果为 null 并且脚本未运行,因为缺少该参数

I believe there's some confusion here.我相信这里有些混乱。 Cheerio is used to parse and manipulate HTML strings, but that's not what your front end code is sending. Cheerio 用于解析和操作 HTML 字符串,但这不是您的前端代码发送的内容。 The string you're telling Cheerio to manipulate has no relationship to the request form payload in any way, nor is it a necessary tool for processing the POST request.您告诉 Cheerio 操作的字符串与请求表单有效负载没有任何关系,也不是处理 POST 请求的必要工具。

You appear to be using JS to submit JSON or form data to the server (as opposed to an HTML form action).您似乎正在使用 JS 向服务器提交 JSON 或表单数据(而不是 HTML 表单操作)。 req.body and req.query would contain this parsed payload respectively, depending on how your server is set up. req.bodyreq.query将分别包含此已解析的有效负载,具体取决于您的服务器设置方式。

Here's an example of how you can set this up using JSON. Note that I've promisified the exec function to avoid blocking the event loop with a synchronous subprocess call.下面是一个示例,说明如何使用 JSON 进行设置。请注意,我已承诺exec function 以避免使用同步子进程调用阻塞事件循环。

Also, the form name and context don't seem to correspond well with subject and body --I assume you'll make this consistent.此外,表单namecontext似乎与subjectbody不太对应——我假设您会使其保持一致。

You'll want to escape and properly quote your subprocess argument string as well.您还需要转义并正确引用您的子进程参数字符串。

public/index.html : public/index.html

<!DOCTYPE html>
<html lang="en">
<head><title>Test</title></head>
<body>
<form>
  <h1>Notify Owner</h1>
  <label>
    <b>Name</b>
    <input id="name" placeholder="Enter your name" required>
  </label>
  <label>
    <b>Message</b>
    <input id="context" placeholder="Enter Reason" required>
  </label>
  <button type="submit">Submit</button>
</form>

<script>
document.querySelector("form").addEventListener("submit", event => {
  event.preventDefault();
  const name = event.target.querySelector("#name").value;
  const message = event.target.querySelector("#context").value;

  fetch("/api/notify", {
    method: "POST",
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({name, message})
  })
    .then(res => {
      if (!res.ok) {
        throw Error(res.statusText);
      }

      return res.json();
    })
    .then(data => {
      console.log(data);
      event.target.reset();
    })
    .catch(err => console.error(err));
});
</script>
</body>
</html>

server.js : server.js

const {promisify} = require("util");
const exec = promisify(require("child_process").exec);
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.static("public"));

app.post("/api/notify", async (req, res) => {
  const {name, message} = req.body; // TODO validate
  // do stuff with name and message
  console.log(name, message);

  try {
    //await exec(`python3 sendEmail.py ${subject} ${body}`);
    res.json({message: "email sent"});
  }
  catch (err) {
    res.json({error: "failed to send email"});
  }
});

app.listen(8000, () => console.log("listening on port 8000"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM