我创建了一个具有表单的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] 删除。
我来说两句