Js study and filing

  javascript, node.js

Recently, I am studying deeply and trying to master it as soon as possible.Node.jsConsider writing an article to record what needs to be recordedConceptMethodas well asCode instanceTo facilitate searching in actual projects. This article will be updated continuously, or another article will be published to discuss more core and key technical issues.

This is a passhttpThe basic example of module communication between client and server is very good, although some places need to be reconstructed and recorded first.

//Client
var http = require('http');
var qs = require('querystring');

function send(theName) {
    http.request({
        host: '127.0.0.1',
        port: 3000,
        url: '/',
        method: 'POST'
    }, function (res) {
        res.setEncoding('utf8');
        res.on('end', function () {
            console.log('\nRequest completed!');
            process.stdout.write('\nyour name:')
        })
    }).end(qs.stringify({name: theName}));
}

process.stdout.write('\nyour name: ');
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (name) {
    send(name.replace('\n', ''))
});
//Server
var http = require('http');
var qs = require('querystring');

http.createServer(function (req, res) {
    var body = '';
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        res.writeHead(200);
        res.end('Done');
        console.log('\ngot name: ' + qs.parse(body).name + '\n');
    })
}).listen(3000);
console.log('Server is running on the port:3000');
var http = require('http');
var qs = require('querystring');
http.createServer(function (req, res) {
    if ('/' === req.url) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end([
            `<form method="POST" action="/url">
            <h1>My form</h1>
            <fieldset>
                <label>Personal information</label>
                <p>What is your name?</p>
                <input type="text" name="name" placeholder="input your name">
                <p><button>Submit</button></p>
            </fieldset>
        </form>`
        ].join(''));
    } else if ('/url' === req.url && 'POST' === req.method) {
        var body = '';
        req.on('data', function (chunk) {
            body += chunk;
        });
        req.on('end', function () {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('<b>Your name is <b>' + qs.parse(body).name + '</b></p>')
        })
    } else {
        res.writeHead(404);
        res.end('Not Found');
    }
}).listen(3000);
console.log('Server is running on the port:3000');