Home > Web Front-end > JS Tutorial > body text

Node.js get, post submit data example code

小云云
Release: 2018-03-06 15:01:15
Original
1255 people have browsed it

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(&#39;views/login.ejs&#39;,{
		},function(err,data){
			res.end(data);
		})
	}
}).listen(8001);
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template