【问题标题】:Client-side calls server to run python客户端调用服务器运行python
【发布时间】:2021-01-06 19:23:26
【问题描述】:

我是个初学者,而且我这几天一直在寻找答案.. 我正在使用 nodejs 构建一个 webapp。

这是 app.js 我要启动的节点(我的服务器端)

http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");


function sendError(errCode, errString, response)
{
  response.writeHead(errCode, {"Content-Type": "text/plain"});
  response.write(errString + "\n");
  response.end();
  return;
}

function sendFile(err, file, response)
{
  if(err) return sendError(500, err, response);
  response.writeHead(200);
  response.write(file, "binary");
  response.end();
}

function getFile(exists, response, localpath)
{
  if(!exists) return sendError(404, '404 Not Found', response);
  fs.readFile(localpath, "binary",
   function(err, file){ sendFile(err, file, response);});
}

function getFilename(request, response)
{
  var urlpath = url.parse(request.url).pathname; // following domain or IP and port
  var localpath = path.join(process.cwd(), urlpath); // if we are at root
  fs.exists(localpath, function(result) { getFile(result, response, localpath)});
}

var server = http.createServer(getFilename);
server.listen(1000);
console.log("Server available..."); 

因此我可以使用localhost:1000/index.html访问我的应用程序

我的 index.html(客户端)是一个 html 页面,其中包含我想用来启动 python 脚本的按钮。

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Lights</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  </head>
  <body class="text-white bg-dark">
  
    <center>
    <input type="submit" value="OFF" name="OFF" onclick="turnOff()">
    <input type="submit" value="ON" name="ON" onclick="turnOn()">
    </center>
    
    <div id="texttest"> </div>
    <div id="fil"> </div>
    
    <script src="funcs.js"></script>
    
  </body>
</html>

从那里你可以看到我使用脚本来运行“onclick()” 这个脚本正在调用 python 运行.. 但显然我不能这样做,因为我正在尝试运行 python 客户端.. ERROR "require not defined"

我的 funcs.js

const { exec } = require('child_process');

function turnOff() {
    console.log("enter Off");
    exec('python3 turnOff.py', (err, stdout, stderr) => {
        if (err) {
            document.getElementById("fil").innerHTML = "error..."+err;
        } else {
            document.getElementById("fil").innerHTML = "running python...";
        }
    });
    document.getElementById("texttest").innerHTML = "trying off sucess  :<br>      " ;
}   
        
function turnOn() {     
    console.log("enter On");
    exec('python3 turnOn.py', (err, stdout, stderr) => {
        if (err) {
            document.getElementById("fil").innerHTML = "error..."+err;
        } else {
            document.getElementById("fil").innerHTML = "running python...";
        }
    });
    document.getElementById("texttest").innerHTML = "trying on sucess  :<br>      " ;
}

我应该使用 AJAX 请求,但我似乎无法找到如何使用它在服务器端运行 python.. 因为 ajax 请求是从 nodejs 中的 html 发送的..

我能做什么?

感谢您的帮助

【问题讨论】:

    标签: python html node.js


    【解决方案1】:

    你的错误是对的

    require 仅在服务器端定义。 funcs.js 在客户端执行,所以不能使用 require。

    您需要进行 AJAX 调用才能达到您的目标。

    // server.js
    
    const { exec } = require('child_process');
    
    const http = require('http');
    
    const server = http.createServer((req, res) => {
      /* When a request will call the http://localhost:5000/run url
       it will execute this code block */
      if (req.url === '/run') {
        exec('python ...', () => {
          // ...
    
          res.write('Python script executed');
          res.end();
        });
      }
    });
    
    server.listen(5000);
    
    // funcs.js
    
    function turnOff() {
        console.log("enter Off");
    
        // Turn off will send a request on the http://localhost:5000/run endpoint
        fetch("/run", {
          method: "POST"
        })
        .then(() => {
           document.getElementById("fil").innerHTML = "running python...";
        })
        .catch(() => {
           document.getElementById("fil").innerHTML = "error..."+err;
        })
    }   
    

    【讨论】:

    • 感谢您的帮助。我不太明白我将如何执行 server.js 以及如何发出 ajax 请求以调用正确的文件来执行...
    • 在您的 app.js 中,您可以使用我发布的代码创建第二个服务器。您可以在一个文件中运行两个 Node.js 服务器。第二种选择是将我的代码放入您的 getFilename 函数中
    • 问题是当我向 /run 发送 ajax 请求时,它被发送到端口 1000,因此返回 404 not found..
    • 我设法让它与 geFilename 函数内的代码一起工作,这样仍然只有一台服务器在端口 1000 上运行,并且 ajax 请求被发送到 /run。如果调用的 url 是 /run,则运行 exec。感谢您的帮助!
    • 您创建了另一个服务器?所以你需要明确指定 URL js fetch("http://localhost:5000/run", { method: "POST" }) 并且在端口 5000 上运行的服务器上你需要添加 js res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888'); stackoverflow.com/questions/18310394/…
    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2012-05-19
    • 2020-06-22
    相关资源
    最近更新 更多