目录

clipboard.png

form.ejs

    <form action="/dologin" method="post">
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <input type="submit" value="登录">
    </form>

get_post.js

  1. post的数据要用req.on('data',function(){})接收
  2. req.method,判断请求是get还是post
var fs = require('fs');
var path = require('path');
var url = require('url');
var ejs = require('ejs');
var http = require('http');

http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
    var method = req.method.toLowerCase();
    var pathname = url.parse(req.url,true).pathname;
    if(pathname == '/login'){
        ejs.renderFile('views/form.ejs',{},function(err,data){
            res.end(data)
        })
    }else if(pathname == '/dologin' && method == 'get'){
        console.log(url.parse(req.url,true).query);
        res.end('dologin');
    }else if(pathname == '/dologin' && method == 'post'){
        var postStr = '';
        req.on('data',function(chunk){
            postStr += chunk;
        })
        req.on('end',function(err,chunk){
            fs.appendFile('login.txt',postStr+'\n',function(err){
                if(err){
                    console.log(err);
                    return;
                }
                console.log('写入数据成功');
            })
            res.end("<script>alert('登录成功');history.back()</script>")
        })
    }else{
        ejs.renderFile('views/index.ejs',{},function(err,data){
            res.end(data);
        })
    }
}).listen(8000)

login.txt

fs.appendFile追加内容到文件
每登录一次,追加一次数据到login.txt

clipboard.png

clipboard.png


渣渣辉
1.3k 声望147 粉丝