Node.js學習備案

whjin發表於2019-02-16

最近在深入學習並爭取儘快掌握Node.js的技術細節,考慮開一篇文章用於記錄需要記錄下來的概念方法以及程式碼例項,方便在實際專案中進行查詢。此篇會持續更新,或另開文章討論更核心、關鍵的技術問題。

這是一個通過http模組進行客戶端和伺服器端通訊的基礎例子,個人覺得很不錯,雖然有些地方需要重構一下,先記錄下來。

//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(`
Request completed!`);
            process.stdout.write(`
your name:`)
        })
    }).end(qs.stringify({name: theName}));
}

process.stdout.write(`
your name: `);
process.stdin.resume();
process.stdin.setEncoding(`utf8`);
process.stdin.on(`data`, function (name) {
    send(name.replace(`
`, ``))
});
//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(`
got name: ` + qs.parse(body).name + `
`);
    })
}).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`);

相關文章