Home > Article > Web Front-end > Node.js get, post submit data example code
This article mainly shares with you the Node.js getpost submission data example code, hoping to help everyone.
demo.js:
//引入http模块 var http=require('http'); var url=require('url'); var ejs=require('ejs'); //ejs模块(第三方模块) 用于视图模板解析 var querystring = require('querystring'); //querystring模块 http.createServer(function(req,res){ res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"}); //获取get 还是post请求 var method=req.method.toLowerCase(); //console.log(method); var pathname=url.parse(req.url,true).pathname; if(pathname=='/dologin' && method=='get'){ //get传值 console.log(url.parse(req.url,true).query); // true表示将get提交的数据转成Json格式 { username: '123', password: '456' } res.end('dologin'); }else if(pathname=='/dologin' && method=='post'){ //post传值 var postStr=''; //该方式只能获取post提交的数据 req.on('data',function(postData){ postStr+=postData; // username=123&password=456 var postJson = querystring.parse(postStr); //username=123&password=456 转成Json对象 console.log(postJson); //Json对象:{ username: '123', password: '456' } res.end("post的数据(username):"+postJson.username+"<br />post的数据(password):"+postJson.password); }) }else{ ejs.renderFile('views/login.ejs',{ },function(err,data){ res.end(data); }) } }).listen(8001);
view/login.ejs:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> </head> <body> <h2>登录</h2> <form action="/dologin" method="get"> <input type="text" name="username"/> <br/> <input type="password" name="password"/> <input type="submit" value="登录"/> </form> </body> </html>
Related recommendations:
$.post submits data and returns data in json format method instance
post displays exception when submitting data How to handle
Four common POST submission data methods
The above is the detailed content of Node.js get, post submit data example code. For more information, please follow other related articles on the PHP Chinese website!