URL Module
Parsing url - query params
node.js
const http = require('http'); const url = require('url'); const server = http.createServer((req, res) => { const queryData = url.parse(req.url, true).query; const smg = queryData.name + ' is ' + queryData.age + ' years old' res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><p>'+ smg +'</html>'); res.end(); }); server.listen(4000); console.log('Server start http://localhost:4000');
Router: http://localhost:4000/?name=Admin&age=30
Kết quả: Admin is 30 years old
URL + FS Module
node.js
const http = require('http'); const url = require('url'); var fs = require('fs'); const server = http.createServer((req, res) => { var q = url.parse(req.url, true); var filename = "." + q.pathname; fs.readFile(filename, function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }); server.listen(4000); console.log('Server start http://localhost:4000');
file
home.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> This is home Page! </body> </html>
Router: http://localhost:4000/home.html
Kết quả: This is home Page!
Router: http://localhost:4000/
Kết quả: 404 Not Found
0 nhận xét:
Post a Comment