如何将输入元素(text / select / radio)的值发送到node.js服务器 [英] How to send values of input elements ( text / select / radio ) to node.js server
问题描述
如何接收单选按钮和选择列表的值并将其放在文件名上?
How can I receive the values of the radio buttons and a select list and put it on the file name?
这是将使用这些值的函数:
This is the function that will be using the values :
router.get('/import', function(req, res, next) {
var csvStream = fastCsv()
.on('data', function(data) {
var report = new csvUploads({
jirakey: data[0],
status: data[1],
priority: data[2],
validity: data[3],
type: data[4],
month: data[5],
defectCategory: data[6],
defectSubCategory: data[7]
});
report.save(function(error) {
console.log(report);
if (error) {
throw error;
}
});
}).on('end', function() {});
const request = req.body;
let month = req.month;
let team = req.team;
const filename = month + ' - ' + team + '.csv';
console.log(res.send(filename));
const csvFilePath = "./uploads/" + filename;
var stream = fs.createReadStream(csvFilePath);
stream.pipe(csvStream);
res.json({
success: 'Data imported successfully',
status: 200
});
});
目前这是我试过的,它在单选按钮和选择列表值中返回 undefined
Currently this is what I have tried, it returns undefined
in both the radio button and select list value
推荐答案
我建议您只是提供视图(importer.html)并将其用作服务器的客户端(使用POST),这样您就可以与服务器交互并在客户端中显示更改/检索到的数据。
I would suggest that you simply serve the view (importer.html) and use it as as a client for your server (using POST), that way you may interact with the server and display the changes/retrieved data back in the client.
您将需要:
-
GET
显示客户的路线。 -
POST
使用客户提交的数据并制作
adecuate响应的路线。 - 服务器回复时做某事的客户逻辑。
GET
route for displaying the "client".POST
route for using the "client submitted data and crafting an adecuate response".- Client logic for doing something when the server replies.
希望这个概念验证(工作示例)能帮助您更好地理解:
Hope this proof-of-concept (working example) will help you understand better :
服务器代码
const express = require('express'); global.app = express()
const bodyParser = require('body-parser')
/* SETUP SERVER CONFIG OPTIONS */
const CONF = {
"htmlDir":__dirname+"/",
"port":3000
}
//----------------------------------------------------------
//.: Server StratUp : Setup Event Handling :.
function InitializeServer(){
console.log("[~] starting ...")
//:[EXPRESS]:MiddleWare
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
//:[EXPRESS]:Router (GET Requests)
app.get("/",RenderImport)
//:[EXPRESS]:Router (POST Requests)
app.post("/import",ImportRequest)
//:[EXPRESS]:Start
app.listen(CONF.port,onSuccessfullStartup)
}
/* Callback example for express successfully listening */
const onSuccessfullStartup=()=>{
console.log("[i] ready & listening","\n http://localhost:"+CONF.port+"/")
}
//----------------------------------------------------------
/* ROUTER EVENT FUNCTIONS : */
const RenderImport=(req,res)=>{res.sendFile(CONF.htmlDir+"importer.html")}
const ImportRequest=(req,res)=>{
console.log("[POST] /import")
console.log(req.body)
if(req.body.stringExample&&req.body.selectExample&&req.body.radioExample){
console.log(" > valid POSTData")
var doSomethingNow={"status":"OK","data":[1,2,3,4,5]}
res.json(doSomethingNow)
}else{
console.log(" > invalid POSTData")
res.json({"status":"ERROR"})
}
}
//----------------------------------------------------------
InitializeServer() // We can now start the server
客户代码(importer.html)
<html><head><title>INDEX</title></head><body>
<center>
<h1>SEND DATA TO SERVER</h1>
<form name="theForm">
<!-- String Example -->
<input name="stringExample" type="text"></input>
<!-- Select Example -->
<select name="selectExample">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<select>
<!-- Radio Example -->
<input type="radio" name="radioExample" value="a" checked> One
<input type="radio" name="radioExample" value="b" > Other
<input type="radio" name="radioExample" value="c" > Another
</form>
<button onclick="SEND()">SEND</button>
</center>
<script>
function SEND(){
var newXHR = new XMLHttpRequest();
newXHR.addEventListener("load",RequestDone);
newXHR.open("POST","/import");
newXHR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
//Fetch Form Data
var form = document.theForm;
var inputx = form.elements["stringExample"];
var select = form.elements["selectExample"];
var radios = form.elements["radioExample"];
//Data for POST
var JSONObj = {}
JSONObj.stringExample = inputx.value
JSONObj.selectExample = select.value
JSONObj.radioExample = radios.value
console.log(JSONObj);
//Format Data for POST
var POSTData = JSON.stringify(JSONObj);
newXHR.send(POSTData);
}
function RequestDone(req){
var res = JSON.parse(req.target.response); console.log(res)
if(res.status=="OK"){alert("Succesfully Sent & Retrieved Data :\n"+res.data.toString())}
else if(res.status=="ERROR"){alert("The server received unexpected data or is missing important parameters")}
else{alert("Unexcpected Error!")}
}
</script>
</body></html>
这篇关于如何将输入元素(text / select / radio)的值发送到node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!