get:
前台代码:<body>
<h1>登录</h1>
<form action="/dologin" method="get">
账号<input type="text" name="username">
密码<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body> 参数传递通过URL传值:
点击登录之后:
后台获取数据代码:var http = require("http")
var url = require("url")
var ejs = require('ejs')
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html;charset='utf-8'"})
var allUrl = req.url;
var parseUrl = url.parse(allUrl,true);
var path = parseUrl.pathname;
if (path == "/login") {//显示登录页面
ejs.renderFile("views/loginPage.ejs",{},function (err,data) {
res.end(data)
})
} else if (path == "/dologin") {//执行登录操作
//后台获取前台get传值数据
console.log(parseUrl.query);//{ username: '111', password: '222' }
res.end("dologin")
} else {//显示index页面
ejs.renderFile("views/index.ejs",{},function (err,data) {
res.end(data)
})
}
}).listen(8000) post:
前台代码:<h1>登录</h1>
<form action="/dologin" method="post">
账号<input type="text" name="username">
密码<input type="text" name="password">
<input type="submit" value="登录">
</form> 点击登录之后url里面没有传值:而是在头文件里面传值
后台获取数据代码:var http = require("http")
var url = require("url")
var ejs = require('ejs')
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html;charset='utf-8'"})
var allUrl = req.url;
var parseUrl = url.parse(allUrl,true);
var path = parseUrl.pathname;
//获取前台的传值方式get还是post
var method=req.method.toLowerCase();
console.log(method);
if (path == "/login") {//显示登录页面
ejs.renderFile("views/loginPage.ejs",{},function (err,data) {
res.end(data)
})
} else if (path == "/dologin"&&method=='get') {//执行登录操作
//后台获取前台get传值数据
console.log(parseUrl.query);//{ username: '111', password: '222' }
res.end("dologin")
} else if (path == "/dologin"&&method=='post') {//执行登录操作
//后台获取前台post传值数据
var postStr='';
req.on("data",function (chunk) {//注意这里回调函数只写一个参数
postStr+=chunk;
})
req.on("end",function (err,chunk) {
console.log(postStr);//username=111&password=222
//后台向前台输出js逻辑:
res.end("<script>alert('登录成功!');history.back()</script>")
})
} else {//显示index页面
ejs.renderFile("views/index.ejs",{},function (err,data) {
res.end(data)
})
}
}).listen(8000)
|