前台提交數據到node服務器(post方式)


post方式同樣有兩種辦法,一種是表單提交,一種是ajax提交。

在此之前需要安裝一個中間件:body-parser,安裝好后在app.js頭部引入:

1 bodyParser = require('body-parser');

並且添加配置代碼:

1 //接收json數據
2 app.use(bodyParser.json()); 3 //extended:true代表可以接收任何數據類型的數據
4 app.use(bodyParser.urlencoded( { extended : true } ));

 1、form提交:

  前台模板文件post.ejs上寫如下代碼:

1 <form action="/reg" method="post">
2         <input type="text" name="name" />
3         <input type="password" name="password" />
4         <input type="submit"  />
5 </form>

  index.js添加一個路由規則:

 1 //添加路徑,通過該路徑響應post.ejs模板
 2 router.get('/post',(req,res) => {  3     res.render('post.ejs');  4 });  5 router.post('/reg',(req,res) => {  6     //req.body 用來接收post方式提交的數據
 7     sql('insert into `user` (`id`,`username`,`password`) values (0,?,?)',[req.body.name,req.body.password],(err,result) => {  8         if (err){  9             console.log('[INSERT ERROR] - ',err.message); 10             return; 11  } 12  res.json({ 13             success : '[INSERT SUCCESS] - '
14  }); 15  }); 16 });

 

2、ajax提交:

  前台模板文件post.ejs寫如下代碼:

 1     <input type="text" name="name" class="name" />
 2     <input type="password" name="password" class="psw" />
 3     <input type="submit" class="submit" />
 4     <script src="/jquery.js"></script>
 5     <script>
 6  $('.submit').click(function () {  7  $.ajax({  8  url : '/reg',  9  type : 'post', 10  data : { 11  name : $('.name').val(), 12  password : $('.psw').val() 13  }, 14  success : function (data) { 15 
16  } 17  }); 18  }); 19     </script>

 

  index.js添加一個路由規則:

  (代碼同上)

 

 

 

 

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM