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

量子位

我创建了一个具有表单的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文件中,例如:

{ "company": "xyzcomp.", "part_no": "xyz001", "date": "01/01/18", "quantity_meter": "0", "amt_paid": "000", "status": "Pending!", "vehicle_name": "farrari", "vehicle_no": "xyxyxyxyxyx", "notes": "problem in saving data!!!" }

现在:我已经创建了html表单,将其与client.js连接,然后将其与server.js连接起来,好吧...但是我可以在客户端脚本中检索表单数据值,并且可以通过服务器端保存数据,但是我没有知道如何将客户端对象发送raw = {...}到服务器程序,以及如何在服务器中检索数据,所以我被所有这些群集弄得一团糟...有谁能帮助您!

悉达思

首先了解

一个新的XMLHttpRequest对象从状态0开始

在对象上成功调用.open()时,状态更改为1

在对象上成功调用.send()时,HTTP请求将发送到.open()中定义的服务器。收到并处理HTTP响应标头后,状态更改为2

最终,来自服务器的响应的实际内容将开始进入。开始时,状态变为3

最后,一旦所有内容下载完毕并准备使用,状态将变为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);
        }
      }

/server.js服务器端代码中。您要提交到url,但在服务器端代码中没有处理程序,而且您正在发出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/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将表单数据从客户端发送到服务器

如何获取Web客户端处理表单,以在不使用客户端脚本的情况下将页面ID信息发送到服务器

将数据从Java客户端发送到Node.js服务器

如何将数据从客户端的html发送到node.js服务器?

如何将客户端数据发送到服务器端

如何使用通过python-socketio从node.js服务器发送到python脚本客户端的值?

将加密的消息从python客户端发送到Node.js服务器

React 和 NodeJS:如何将数据从服务器发送到客户端?

如何在Node.js中将文件从服务器发送到客户端

如何将通知从node.js服务器发送到android客户端。

如何通过进行Ajax调用将html表单数据发送到node.js服务器?

如何使用 Python 将数据从客户端套接字发送到服务器套接字?

服务器如何使用Java将消息发送到客户端

如何使用C ++中的Websocket客户端将消息发送到服务器?

如何使用带代理的Signalr将消息从客户端发送到服务器?

如何使用angular将表单数据发送到服务器?

如何使用Volley将JSONObject作为表单数据发送到服务器

如何使用angular 2将表单数据发送到服务器api?

如何使用节点js将选定的下拉元素从客户端发送到服务器-Express

如何将数据从服务器端 (Express.js) 发送到客户端 (React.js)?

gRPC 中数据如何从客户端发送到(多服务)服务器

如何从服务器读取数据并将数据发送到客户端?

如何将Spring Boot管理客户端元数据发送到管理服务器

如何将数据(字符串)从HTTP客户端发送到服务器

如何在不阻止服务器的情况下通过tcp将数据发送到客户端?

Angular2:发出请求时如何将数据从客户端发送到服务器

如何将数据从UDP服务器发送到NAT后的UDP客户端?

如何将多个数据流从单个客户端发送到TCP服务器

如何将数据发送到多线程服务器上的特定客户端