javascript - 如何使用node.js将表单数据从客户端脚本发送到服务器脚本

标签 javascript html json node.js ajax

我创建了一个带有表单的 html 页面,我需要的是获取用户输入并将其保存在 json 文件中,但我把事情搞砸了!..

我使用express模块​​来创建服务器。 我把脑子里的所有东西都搞乱了,比如 ajax、node js 和 p5.js 所有这些......

让我们看看我的代码:

var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
console.log('Server Running... at:\nhttp://localhost:3000/  or,\nhttp://127.0.0.1:3000/\nPress ctrl+c to quit!\n');

var fs = require('fs');
var data = fs.readFileSync('public/json/receive.json');
var allForms = JSON.parse(data);
console.log(allForms);

// here in server i need the raw object, to process the file with raw object's dara...
//console.log('raw: ' + raw)

//allForms = allForms + raw

//data = JSON.stringify(allForms, null, 2)
//fs.writeFile('public/json/receiving.json', data, log);
//function log(end) {
//  console.log('File is successfully saved!')
//}
<form method="POST" onsubmit="return put_json(this);">
  <label style="margin-left: 6em;"> M/s: </label>
  <input type="text" name="company" style="margin-left: 7em;" />
  <label style="margin-left: 17.7em;"> Part Number: </label>
  <input type="text" name="part_no" style="margin-left: 3.4em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Receiving Date: </label>
  <input type="Date" name="date" style="margin-left: 0em;" />
  <label style="margin-left: 17.5em;"> Quantity(Meter): </label>
  <input type="Number" name="quantity_meter" value="0" style="margin-left: 1em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Amount Paid: </label>
  <input type="Number" name="amt_paid" value="0" style="margin-left: 1.8em;" />
  <label style="margin-left: 17.5em;"> Status: </label>
  <input type="text" name="status" value="Pending!" style="margin-left: 8em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Vehicle Name: </label>
  <input type="text" name="vehicle_name" style="margin-left: 1em;" />
  <label style="margin-left: 17.4em;"> Vehicle Number: </label>
  <input type="text" name="vehicle_no" style="margin-left: 1.5em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Add Notes: </label>
  <textarea name="notes" style="margin-left: 2.7em;">(If Any..)</textarea>
  <br>

  <input id="submit" type="submit" value="Save" style="margin-left: 75em;" />
</form>
<script>
  function requestHandler(data) {
    var Request = new XMLHttpRequest();
    var url = '/server.js';
    Request.open('POST', url, true);
    Request.onreadystatechange = sendData(Request, data);
  }

  function sendData(rqst, DATA) {
    if (rqst.readyState == 4 && rqst.status == 200) {
      alert('Sending Data To Server ...');
      packet = JSON.stringify(DATA, 0, 4);
      console.log('packet: ' + packet);
      rqst.send(packet);
    } else {
      alert('Connection FAIL,\nCheck connection and Retry !!!');
      console.log(rqst);
    }
  }


  var raw;

  function put_json(form) {
    raw = {
      'company': form.company.value,
      'part_no': form.part_no.value,
      'date': form.date.value,
      'quantity_meter': form.quantity_meter.value,
      'amt_paid': form.amt_paid.value,
      'status': form.status.value,
      'vehicle_name': form.vehicle_name.value,
      'vehicle_no': form.vehicle_no.value,
      'notes': form.notes.value
    }
    console.log('raw: ' + raw);

    requestHandler(raw);

    return false;
  }
</script>

我想将其保存在 json 文件中,例如:

{ "公司": "xyzcomp.", "part_no": "xyz001", “日期”:“01/01/18”, “数量计”:“0”, “amt_paid”:“000”, "status": "待处理!", “vehicle_name”:“法拉里”, "vehicle_no": "xyxyxyxyxyx", "notes": "保存数据时出现问题!!!" }

现在:我已经创建了 html 表单,将其与 client.js 连接,然后与 server.js 连接,ok... 但我可以在客户端脚本中检索表单数据值,并且可以通过服务器端保存数据, 我不知道如何将客户端对象 raw = {...} 发送到服务器程序如何检索服务器中的数据,所以我对所有这个集群感到困惑...... 有谁可以帮忙吗!

最佳答案

首先了解一下

A new XMLHttpRequest object starts in state 0

When you successfully call .open() on the obect, the status changes to 1

When you successfully call .send() on the object, an HTTP request goes off to the server defined in .open(). Once the HTTP response headers have been received and processed the status changes to 2

Eventually, the actual content of the response from the server will start coming in. When this begins, the status changes to 3

Finally, once all of the content is downloaded and is ready to be used, the status changes to 4

根据我的观察,有一些缺失的部分: 在你的客户端

var Request = new XMLHttpRequest();
    function requestHandler(data) {
        var url = '/server.js';
        Request.open('POST', url, true);
        Request.onreadystatechange = sendData;
        Request.send(data);
    /*unless .send() is called, nothing moves forward..there will be no communication between the client and server,so here it also means when the request ready state changes from 1 to 2 , call sendData, similarly when it goes from 2 to 3 call sendData, and similarly for 3 to 4 , unless you dont call Request.send how will the readystate change, if readystate is not changing why will sendData be called at all.*/
      } 
       function sendData() {
        /*4 means request is complete , if you don't call `Request.send(data)` like I have in the previous function, in the line above ,then it means you have not even started the request (which is 1), if 1 is not even reached in the ready state, how can you check for 4 or for status 200. You must send first , so that ready state changes and sendData is called*/
        if (Request.readyState == 4 && Request.status == 200) {
          alert('Data sent ...');
        } else {
          alert('Connection FAIL,\nCheck connection and Retry !!!');
          console.log(Request);
        }
      }

在您的服务器端代码中。您正在提交到 url /server.js 但是在您的服务器端代码中,您没有处理程序,而且您正在发出 POST 请求,这很好。 在您的服务器中您需要添加的是

app.js

var express = require('express');
var app = express();
app.listen(3000);
app.use(express.static('public'));
console.log('Server Running... at:\nhttp://localhost:3000/  or,\nhttp://127.0.0.1:3000/\nPress ctrl+c to quit!\n');
//let's say we make a file to handle this request
const serverRouteHandler = require("./serverRouteHandler")
app.use('/server.js',serverRouteHandler)

serverRouteHandler.js

const router = require('express').Router();
router.post('/',function(req,res){
  const rawBodyFromClient = req.body
  console.log(JSON.stringify(rawBodyFromClient,null,2))//this will print the JSON to your server console, not the stringify here is just for representational purposes.
 res.send()//do not forget this line, if you miss this then it means on your client side the readyState will never reach 4 and will be stuck at 3 and you will get a blank HTTP status coz your request never completed in the first place.
})
module.exports = router;

为了简洁起见,我假设您的 app.js 和 serverRouteHandler.js 位于同一目录中。 如果您想监控请求的进度,我建议您查看这篇文章。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

关于javascript - 如何使用node.js将表单数据从客户端脚本发送到服务器脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48712140/

相关文章:

php - 针对不同尺寸对齐/排序 HTML 中的图像

javascript - 根据下面的 div 颜色更改粘性导航颜色

html - 字符溢出容器

javascript - 如何在网站中重复使用重复的 HTML?

javascript - Chrome Extension API : chrome. tabs.captureVisibleTab 在后台页面到内容脚本

javascript - 如何在Jquery ajax中读取名称和值对中的JSONP响应数据?

python - Pandas 将 Dataframe 转换为嵌套的 Json

javascript - Javascript 中具有相同 Id 的多个元素

java - Android 应用中的 HTML/JS 应用

javascript - 如何将 Css 属性的值(高度以 px 为单位)存储在 Javascript 变量中作为数字?