Sử dụng form trong nodejs

Sử dụng form trong nodejs hướng dẫn cách nhận dữ liệu trong form do client gửi lên, cách nhận và lưu các file trong form giúp bạn code với các views một cách nhanh chóng. EJS là một template được dùng phổ biến trong nodejs.



Tổ chức để nhận dữ liệu từ form

NodeJS chạy ở phía server, do đó sẽ có lúc bạn cần phải nhận dữ liệu gửi lên từ các form. Muốn vậy thì dùng module body-parser và chỉ định encode như sau

//index.js
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:true})); 

Sau khi đã nạp body-parser như trên, tiếp theo bạn tạo 1 file view chứa form gì đó. Tag form phải có thuộc tính action trỏ lên 1 route sẽ nhận dữ liệu khi user submit. Code tham khảo như sau

<!-- addEmail.ejs -->
<form action="/addEmail" method="post">
    <input name="email">
    <button type="submit">Add Email</button>
</form>

Việc tiếo theo cần tạo route để nạp file view mới tạo

app.get('/addEmail', (req, res)=>{
    res.render("addEmail.ejs");
})

Cuối cùng tạo route để nhận dữ liệu. Code trong đây bạn dùng req.body để lấy dữ liệu trong form gửi lên, từ đó xử lý thế nào là tùy ý.

app.post('/addEmail', (req, res)=>{
    let email  = req.body.email;
    res.send(email);
})

Upload file trong form

Để có thể upload file từ form, bạn cần cài thêm module . Có nhiều module giúp bạn việc này. Sau đây là hướng dẫn cài và sử dụng module formidable.

  • Cài đặt module formidable
npm install formidable
  • Nhúng module vào trang, nên nhúng luôn module file sytem (fs) để tiện các thao tác trên file đã upload
//index.js
var formidable = require('formidable');
var fs = require('fs');
  • Tạo 1 view chứa form. Tag form phải có thuộc tính  enctype=”multipart/form-data” , trong form có tag <input type=”file”> và form phải có thuộc tính action trỏ lên 1 route sẽ nhận dữ liệu
<!-- addproduct.ejs --> 
<form action="/addnewprod" method="post" class="form" enctype="multipart/form-data" >
  <p>Tên SP <input type="text" name="productName"> </p>
  <p>HìnhSP <input type="file" name="productImage"> </p>
  <p> <input type="submit" value="Thêm sản phẩm"> </p>
</form>
  • Tiếp theo cần tạo route để nạp view chứa form vừa tạo ở trên:
app.get('/addprod', (req, res)=>{
    res.render("addproduct.ejs");
})
  • Việc tiếp theo là tạo 1 folder để chứa hình sẽ upload
  • Cuối cùng là tạo route để nhận dữ liệu từ form , lưu hình
app.post("/addnewprod",(req, res) =>{
    var form = new formidable.IncomingForm();  
    form.parse(req, function (err, fields, files) {
     let name = fields.productName;      
     let tmpPath = files.productImage.filepath;     
     let tenFile = files.productImage.originalFilename;
     let destPath =  __dirname +'\\public\\images\\' + tenFile; 
     fs.rename(tmpPath, destPath, function (err) {  //copyFile
       if (err) throw err;
       res.end('File đã upload');
     });
      //res.end(JSON.stringify({ fields, files }, null, 2));
      res.send("Name=" + name);
    });
})

Biến fields trong hàm parse chứa các form field bình thường trong form, còn biến files trong hàm parse thì chứa các file được upload. ba

Xem thêm: https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp

Xoá file: Sẵn tiện cần biết luôn cách xóa 1 file , bạn sử dụng module fs :  var fs=require(‘fs’); và dùng hàm unlink để thực hiện xoá

app.get("/delete",(req,res)=>{
    pathfile="/images/a.png";
   fs.unlink(pathfile, function (err) {
      if (err) throw err;
      console.log('File deleted!');
      res.send("File đã xóa");
   });
});

Việc sử dụng form trong nodejs cũng dể phải không nào. Đọc thêm tài liệu về các module formidable , fs nhé: https://www.npmjs.com/package/formidable , https://nodejs.org/api/fs.html