如何将输入元素(text / select / radio)的值发送到node.js服务器

时间:2018-04-04 04:46:15

标签: javascript node.js express

如何接收单选按钮和选择列表的值并将其放在文件名上?

这是将使用值的函数:

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

2 个答案:

答案 0 :(得分:1)

而不是

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

尝试

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

答案 1 :(得分:0)

我建议您只是提供视图(importer.html)并将其用作服务器的客户端(使用POST),这样您就可以与服务器进行交互并将更改/检索到的数据显示在客户端。

你将需要:

  1. GET显示“客户”的路线。
  2. POST路由使用“客户端提交的数据并制作一个 充实的回应“。
  3. 客户端逻辑,用于在服务器回复时执行某些操作。
  4. 希望这个概念验证(工作示例)能帮助您更好地理解:

      

    服务器代码

    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>