មេរៀនយើងតពីមេរៀន ប្រើ frameworks express ឲឡូវនេះមកសិក្សា read file ដោយបានសិក្សារពី method post និង get។
យើងបង្កើត file html មួយដោយមានឈ្មោះថា index.html ហើយបានបង្កើតជា form
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>form</title></head><body><h1>Calculater</h1><form action="/" method="post"><input type="text" name="num1" placeholder="input nuber A"><input type="text" name="num2" placeholder="input nuber B"><button>Calculate</button></form></body></html>
mehtod get()
នៅក្នុង file server.js ដោយយើងប្រើ method get ដើម្បីទាញ file html
យើងបានដឹងមកហើយពីមេរៀនមុនយើងបាន បង្ហាញអក្សរនៅ body ដោយយើងប្រើ property send()។ ប៉ុន្តែចំពោះ file វិញប្រើជាមួយ method sendFile()
វិធីស្វែងរកទីតាំង folder ដែលផ្ទុក file ឬហៅថាបង្កើត path
console.log(__dirname)
បន្ទាប់មកយើងតជាមួយ file របស់យើង
const express = require('express'); // Create core moduleconst app = express();app.get('/', (req,res)=>{// MARK: '/' home routeres.sendFile(__dirname + "/index.html")})app.listen(3000, ()=>{console.log("Server started on port 3000");});
mehtod post()
ប្រសិនជាយើងបញ្ចូលលេខរួចហើយយើងចុចប៉ូតុន calculet នោះវានឹងផ្ទាំងមួយថា cannot POST
const express = require('express'); // Create core moduleconst app = express();/*MARK: method */app.get('/', (req,res)=>{// MARK: '/' home routeres.sendFile(__dirname + "/index.html")})/*MARK: method post */app.post('/', (req,res) => {res.send("<h1>Thank you for using!</h1")})app.listen(3000, ()=>{console.log("Server started on port 3000");});
ដើម្បីចាប់ value ពី file html យើងត្រូវប្រើ package មួយឈ្មោះថា body-parser។ សូម install body-parser
npm install body-parser
ក្រោយពីយើង install វារួចហើយ យើងត្រូវបង្កើត module
const bodyParser = require('body-parser') // Create module of body-parser
bodyParser វាដើរជាមួយ app របស់ express យើងត្រូវសរសេរ
app.use(bodyParser.urlencoded({extended: true}))
ចំពោះ app.use(bodyParser.វាអាចមានច្រើប្រភេទ មានដូចជា text , json ។ល។ ប៉ុន្តែចំពោះ html យើងប្រើ urlendcoded)
{extended: true}) វាអនុញ្ញាតឲ្យយកទិន្ន័យពី file html បាន
const express = require('express'); // Create core module const bodyParser = require('body-parser') // Create module of body-parser const app = express(); app.use(bodyParser.urlencoded({extended: true})) /*MARK: method */ app.get('/', (req,res)=>{ // MARK: '/' home route res.sendFile(__dirname + "/index.html") }) /*MARK: method post */ app.post('/', (req,res) => { console.log(req.body) let n1 = Number(req.body.num1) let n2 = Number(req.body.num2) let result = n1 + n2 res.send(`<h1>Result of calculate is : ${result}</h1>`) }) app.listen(3000, ()=>{ console.log("Server started on port 3000"); });
let n1 = Number(req.body.num1) ចំពោះ Number ដោយសារយើងបញ្ចូលជាតំលៃជាលេខដូចនេះយើងប្រើ type number
0 Comments