如何将数据从hbs(html)传递到axios发布请求?

时间:2019-04-12 03:15:57

标签: html node.js express handlebars.js axios

对于nodejs和Express来说是新事物。

我想在按“提交”按钮时将用户输入的数据作为电子邮件发送到axios.post请求的数据。 我已经检查了axios请求中的硬编码数据是否正常。

data_email.hbs

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <div>
        <div>
            <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
                <ul class="nav navbar-nav">
                    <li><a href="/home">Home</a></li>
                    <li><a href="/about">About us</a></li>
                    <li class="active"><a href="/data_email">Data by Email<span class="sr-only">(current)</span></a></li>    
                </ul>
            </nav>
        </div>

        <div class="container">
            <h3>Employee Data Search</h3>
            <label for="email">Enter the employee's cloud-spartan.com email</label></br>
            <input type="email" id="email" size="30">
            <input type="submit" value="search">
            <div class ="employee-data">
                ({data})
            </div>
        </div><!-- container -->
    </div>
</body>
</html>    

server.js

app.get("/data_email", function(req,res){
  queries = req.query;
  if(queries){
    axios.post(url_post,
      post_data, //get the data (email) from data_email.hbs
      post_config, 
      {params: queries}
    ).then(function (response){
      json_result_post = response['data'];
      content = json_result_post['body-json'];
      //console.log(content);
      data_table = JSON.stringify(content, null, 2);
      res.render("data_email", {data:data_table});
    }).catch(function (error){
      console.log(error);
    });
  }
  else {
    console.log("???");
  }
}); 

1 个答案:

答案 0 :(得分:0)

您应该在form中用html按钮插入submit

<div class="container">
  <form action="/data_email" method="POST">
    <input type="text" id="email" value="">
    <input type="submit" value="Submit">
  </form>
</div>

并且您的服务器应侦听POST方法而不是GET。您还需要body-parser来解析传入的x-www-form-urlencoded请求主体。然后可以通过req.body

获得表单输入
const bodyparser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }));

app.post("/data_email", function(req,res) {
  console.log(req.body)
  // contains input, example req.body.email

更新:

您可以使用具有相同api名称但http methods不同的端点。因此,您可以执行以下操作来提供表格

app.get("/data_email", function(req,res){
  res.render("data_email", {data:data_table});
}