簡體   English   中英

如何將數據從我的節點腳本發送到客戶端腳本中的函數

[英]How to send data from my node script to a function in the client script

我正在嘗試通過構建自己的庫存管理系統來學習Node.JS。 我正在嘗試學習如何將數據從HTML頁面和客戶端JS腳本傳遞到服務器,然后將數據返回到客戶端JS腳本。

到目前為止,我已經使用該表單創建了基本的HTML頁面,創建了客戶端JS腳本和Index / Server JS腳本。 服務器是節點,並使用nedb作為數據庫和webpack。

我當前的問題是我無法將數據從HTML表單發送到服務器以轉到Client.js函數。 我嘗試使用response.sendFile和其他一些響應。 命令,但是服務器一直說response.x不是函數(x是sendfile / render / etc ...)。 我不確定自己在做什么錯,我包括了HTML表單,服務器腳本和客戶端功能。

的HTML

<div>
    <form action='/inventory' method='POST'>
           <input type="text" name='Name' value="Name"/>
           <input type="text" name='Model-Num' value="Model Number"/>
           <input type="text" name='Current-Stock' value="Current Stock Amount"/>
           <input type="text" name='Target-Stock' value="Target Stock"/>
           <input type="text" name='Reorder-Amount' value="Reorder Amount"/>


            <input type="submit" value="Submit"/> 
    </form>

</div>

=============================

服務器

app.post('/inventory', urlencodedParser ,(req, response, next) => {

  console.log('Im not broken');

  console.log("I got a req");
  console.log(req.body)

  response = {
      status: "success",
      code : 200,
      hype : "SO hyped",
  }

  console.log("res" , response);

  next();


});

=======================

客戶

function printHTML(e)
{
    console.log("e " , e);
}

我只希望來自節點功能的數據對象轉到客戶端功能。

您需要response.status(200).json(您的對象)。 路由處理程序中不需要next()。

一個主要問題是,您無法使用客戶端Javascript從服務器接收響應。

您以前聽說過AJAX嗎? 如果沒有,那么看看它。 使用AJAX,您可以進行服務器調用並從服務器獲取響應。 在當前代碼中,您無法接收服務器響應。

另外,您有參數response ,然后再

response = {
    status: "success",
    code : 200,
    hype : "SO hyped",
}

覆蓋參數。 這樣, response不再具有參數(render,sendFile等)的功能,而是具有您定義的對象的功能。 因此,絕對有必要重命名參數或對象。

您正在覆蓋您的響應對象,該對象作為參數從路由處理程序傳遞。 嘗試使用其他變量名,以免覆蓋它。

app.post('/inventory', urlencodedParser, (req, response, next) => {
  console.log('Im not broken');
  console.log("I got a req");
  console.log(req.body);

  const returnToClient = {
    status: "success",
    code: 200,
    hype: "SO hyped"
  };

  // You could also use response.send() here, but your response is an 
  // object so it's better to use response.json()
  response.json(returnToClient);
});

同樣,如果您將響應發送回客戶端,那么您實際上就不需要使用next()函數。

暫無
暫無

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

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