簡體   English   中英

如何將此動態 index.html 頁面轉換為 React 頁面並將其連接到同一個 Nodejs express 頁面?

[英]How to convert this dynamic index.html pages to a React page and connect it to the same Nodejs express page?

我有一個 NodeJs 后端和一個 React 前端。 我面臨的主要問題是從 React 前端獲取數據並將其發送到后端並等待 Node js express 后端執行。 我可以使用一個簡單的 html 頁面來做到這一點,但不能使用 React 來做到這一點。 歡迎提出反應建議。 我在端口 4500 上運行 NodeJs,在端口 3000 上運行 React。

下面我附上 HTML 代碼和 NodeJS 代碼,它們在托管在端口 4500 上時運行良好並給出結果。 但我的 React 需要類似的東西。 我對 React 完全陌生,所以我很掙扎。 任何幫助都將在 React 前端頁面上得到贊賞!

我要做的是->

  1. 帶有提交按鈕的簡單文本框
  2. 提交后,Node js express 后端使用提交的數據執行。
  3. output 將是一個 html 表,我想在搜索框下方的 iframe 中顯示該表。

我可以在 html、js 和 Nodejs 中做到這一點。 但我想在 react js 中做前端。 下面我編寫了 React js 代碼,但無法使其工作。

輸入 HTML 頁面<index.html>

    <body>
        <div>
          <header>
            <h1>Project</h1>
          </header>
        <div class="container">
          <div class="table-responsive">
          <form id="inputData" action="/search" method="POST" align="center">
          <input
            type="text"
            name="newItem"
            id="newItem"
            placeholder="What are you looking for?"
            width="50%"
            class="form-control"
          />
          <br/>
          <div align="center">
            <button type="submit" name="button" id="button" class="btn btn-info" ">Search</button>
          </div>
        </div>
      </form>
      <br/>
      </div>
      <footer>
        <p>Copyright ⓒ <span id="year"></span> Project</p>
      </footer>
      </div>
        <script>
          document.getElementById("year").innerHTML = new Date().getFullYear();
          </script>
      </body>

后端 NodeJs 頁面(server.js)

    const express = require("express");
    const bodyParser = require("body-parser");
    const shelljs = require("shelljs");
    var cors = require("cors");

    const app = express();
    const { exec } = require("child_process");

    app.use(cors());
    app.use(express.static("public"));
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());

    app.get("/", function (req, res) {
      res.sendFile(__dirname + "/public/index.html");
    });

    app.post("/search", async function (req, res) {
      console.log("--------- Dirname -----" + __dirname);
      console.log("Entered the shell section");
      const data = req.body.newItem;
      exec(
        `cd /home/user/Desktop/Project/test; sh run.sh "${data}"`,    async (err, stdout, stderr) =>                         {
          if (err) console.error(err);
          console.log(stdout);
          exec("python3 csv_to_html.py", (err, stdout, stderr) => {
            console.log(stdout);
            res.sendFile(__dirname + "/public/search.html");
            console.log(":: End game ::");
          });
        }
      );
    });

    app.get("/output", function (req, res) {
      res.sendFile(__dirname + "/output.html");
    });

    app.listen(4500, function () {
      console.log("Server starting at port 4500...");
    });

結果顯示 HTML 執行后端后的頁面(search.html)

    <body>
        <div>
          <header>
            <h1>Project</h1>
          </header>
        <div class="container">
          <div class="table-responsive">
          <form id="inputData" action="/search" method="POST" align="center">
          <input
            type="text"
            name="newItem"
            id="newItem"
            placeholder="What are you looking for?"
            width="50%"
            class="form-control"
          />
          <br/>
          <div align="center">
            <button type="submit" name="button" id="button" class="btn btn-info" ">Search</button>
          </div>
         </div>
        </form>
        <br/>
        <div id="table">
        <iframe src="http://localhost:4500/output" frameborder="0" width="100%" class="myIframe">        
        </iframe>
        </div>
        </div>
        <footer>
        <p>Copyright ⓒ <span id="year"></span> Project</p>
        </footer>
      </div>
      <script>
          document.getElementById("year").innerHTML = new Date().getFullYear();
      </script>
    </body>
    <script type="text/javascript">
    $(document).ready(function(){
      $('#table').show();
    });
    </script>
    <script type="text/javascript" language="javascript">
      $(".myIframe").css("height", $(window).height() + "px");
    </script>

當我在端口 4500 上運行它並且我能夠得到結果時,我的代碼工作得非常好。 我想用 React Js 作為我的前端,用同樣的 Node js express 作為我的后端來做同樣的事情。 我無法編寫完美的 React 代碼。 在這里,我發布了我為上述 HTML 編寫的代碼,但無法達到預期的結果。 任何人都可以幫忙嗎?

反應 Js 代碼<App.jsx>

    import React from "react";
    import Button from "react-bootstrap/Button";
    import axios from "axios";

    function App() {
      const year = new Date().getFullYear();
      return (
        <div>
          <header>
            <h1>Project</h1>
          </header>
          <div className="container">
            <form onSubmit={e => clickButton(e)}>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control"
                  id="searchData"
                />
              </div>

              <button type="submit" className="btn btn-primary">
                Search
              </button>
            </form>
            <br />
          </div>
          <footer>
            <p>Copyright ⓒ {year} Project</p>
          </footer>
        </div>
      );
    }

    function clickButton(e) {
      //alert("Works fine");
      //console.log("Works fine");
      e.preventdefault();
      let body = {
        newItem: document.getElementById("searchData").value
      };
     const postRequest = async () => {
         let res = await axios
           .post("http://localhost:4500/search", body)
           .then(response => {
             alert(response);

           })
           .catch(function (error) {
           console.log(error);
           });
       };
       postRequest();
    export default App;

您可以嘗試使用 HashRouter 或 BrowserRouter。 首先有 2 個頁面用於您的 react 應用程序,1 個用於索引,另一個用於您的搜索頁面。 在您的服務器端,只需返回成功狀態。 react 應用在收到成功狀態后可以切換到帶有 window.location.href 或 window.location.hash 的搜索頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM