如何通过nodejs 使用 GET 或 POST 请求发送数据

server.js

var http = require('http');
var fs = require('fs');
var url=require('url');
var querystring = require('querystring');//json 形式转化 a=b  a:b
function startServer(route, handle) {
    var onRequest = function(request, response) {
        var pathname=url.parse(request.url).pathname;//不包括问好的
        console.log('Request received ' + pathname);
        //表单是post所以用以下方法解决
        var data='';
        request.on("error", function(err){
            console.error(err);
        }).on("data",function(chunk){ data+=chunk;}
        ).on("end",function(){
            if(request.method=='POST')
             {
            route(handle, pathname, response,JSON.stringify(querystring.parse(data)));
             }
            else{
                var parms=JSON.stringify(url.parse(request.url,true).query);
                console.log(parms)
                route(handle, pathname, response, parms);
            }
        })

        // var queryy=url.parse(request.url,true).query//问好的东西
        // console.log(queryy);
        // route(handle,pathname, response,queryy);
    }

    var server = http.createServer(onRequest);

    server.listen(3000, '127.0.0.1');
    console.log('Server started on localhost port 3000');
}

module.exports.startServer = startServer;

app.js

var server  = require('./server');
var router = require('./router');
var handler = require('./handler');

var handle = {};
handle["/"] = handler.home;
handle['/home'] = handler.home;
handle['/review'] = handler.review;
handle['/api/v1/records'] = handler.api_records;

server.startServer(router.route, handle);

handler.js

var fs=require('fs');
 function home(response)
 {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    fs.createReadStream(__dirname + '/index1.html', 'utf8').pipe(response);
 }
 function review(response) {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    fs.createReadStream(__dirname + '/review.html', 'utf8').pipe(response);
}

function api_records(response,query) {
    response.writeHead(200, { 'Content-Type': 'application/json' });
    console.log(query);
    response.end((query));
}

module.exports = {
    home: home,
    review: review,
    api_records: api_records
}

router.js

var fs=require('fs');
function route(handle,pathname,response,query)
{
    console.log('routing'+pathname);
    if(typeof handle[pathname]=='function')
    {
        handle[pathname](response,query);
    }
    else{
    response.writeHead(200, { 'Content-Type': 'text/html' });
    fs.createReadStream(__dirname + '/404.html', 'utf8').pipe(response);
}
}
 module.exports.route=route;

index1.html




    
    
    
    Document


    
name: password:

如何通过nodejs 使用 GET 或 POST 请求发送数据_第1张图片
在这里插入图片描述
如何通过nodejs 使用 GET 或 POST 请求发送数据_第2张图片

你可能感兴趣的:(如何通过nodejs 使用 GET 或 POST 请求发送数据)