如何使用node.js

时间:2018-02-09 18:38:08

标签: 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文件中,如:

{ "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 = {...}发送到服务器程序如何检索服务器中的数据,所以我搞砸了所有这个集群... 是否有人可以提供帮助!

2 个答案:

答案 0 :(得分:2)

如果您只想在文本文件中编写json,请使用此函数。这肯定会起作用。

function saveFile(text, name, type) {
    var a = document.createElement("a");
    var file = new Blob([text], {type: type});
    a.href = URL.createObjectURL(file);
    a.download = name;
    a.click();
}

 saveFile(JSON.stringify(jsonData), 'test.txt', 'text/plain');

答案 1 :(得分:2)

首先了解

  

新的XMLHttpRequest对象从状态0开始

     

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

     

当您在对象上成功调用.send()时,会发出HTTP请求   off到.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 但是在你的服务器端代码中你没有处理程序,而且你发出了一个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