发送HTTP请求(GET,POST)

获取 get 传值:

get 方式获取登录表单:

 

 

获取 post 传值:

 

const http = require('http');
const url = require('url')
const ejs = require('ejs')
const staticWeb = require('./web')

http.createServer(function (request, response) {
    //创建静态Web服务
    staticWeb(request,response,'./static')
    //路由
    let pathname = url.parse(request.url).pathname

    if (pathname == '/') {
        //假如路径为http://127.0.0.1:8081/?userName=jack&age=16
        console.log(request.method) // //获取请求类型 GET
        let query = url.parse(request.url, true).query
        console.log("get query:", query) //{ userName: 'jack', age: '16' }
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end('<h3>获取get传值成功</h3>');
    }
    else if(pathname=='/login'){
        console.log("login",request.method) //获取请求类型 GET
        ejs.renderFile('./views/form.ejs',{},(err,data)=>{
            response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            response.end(data);
        })
    }
    else if(pathname=='/doLogin'){
        console.log("doLogin:",request.method) //POST
        let params='';
        request.on('data',(chunk)=>{ //post方式传值是以流的方式传
            params+=chunk;
        })
        request.on('end',()=>{
            console.log(params)
            response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            response.end(params)
        })
    }
    else if(pathname=='/register'){
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>执行注册逻辑</h3>");
    }
    else if(pathname=='/loginOut'){
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>执行退出登录逻辑</h3>");
    }
    else{
        response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>404 Not Found</h3>");
    }
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

  

posted @ 2021-02-02 00:14  shanlu  阅读(440)  评论(0编辑  收藏  举报