How to send values of input elements ( text / select / radio ) to node.js server

佐手、 提交于 2020-01-02 10:08:11

问题


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
  });
});

Currently this is what I have tried, it returns undefined in both the radio button and select list value


回答1:


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.

You will be needing :

  1. GET route for displaying the "client".
  2. POST route for using the "client submitted data and crafting an adecuate response".
  3. Client logic for doing something when the server replies.

Hope this proof-of-concept (working example) will help you understand better :

SERVER CODE

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

CLIENT CODE (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>



回答2:


instead of

 const request = req.body;
 let month = req.month;
 let team = req.team;

try

 const request = req.body;
 let month = request.month;
 let team = request.team;


来源:https://stackoverflow.com/questions/49642976/how-to-send-values-of-input-elements-text-select-radio-to-node-js-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!