[nodejs] get post
get
const http = require('http'); const url = require('url'); const host = 'http://localhost:3000'; http.createServer(function (req, res) { const { searchParams } = new URL(req.url, host); console.log(searchParams); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(searchParams.toString()); }).listen(3000); console.log(`Server running at ${host}`);
post
login.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/doLogin" method="post"> 用户名:<input type="text" name="username"><br> 密码: <input type="password" name="password"><br> <input type="submit" value="提交"> </form> </body> </html>
server.js
const http = require('http'); const ejs = require('ejs'); const host = 'http://localhost:3000'; http.createServer(function (req, res) { const { url } = req; if (url === '/login') { ejs.renderFile('./login.ejs', {}, (err, data) => { if (!err) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(data); } }) } else if (url === '/doLogin') { let postData = ''; req.on('data', (chunk) => { postData += chunk; }); req.on('end', () => { console.log(postData); res.end(postData); }); } }).listen(3000); console.log(`Server running at ${host}`);