Node.js 中的重要API:HTTP
2019-12-16
21:04:14
require('http').createServer(function (req, res) { res.writeHead(200); res.end('Hello World'); }).listen(3000);
require('http').createServer(function (req, res) { res.writeHead(200,{'Content-Type':'text/html'}); res.end('Hello <b>World</b>'); }).listen(3000);
require('http').createServer(function (req, res) { 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">' , '<p><button>Submit</button></p>' , '</form>' ].join('')); }).listen(3000);
require('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">' , '<p><button>Submit</button></p>' , '</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('<p>Content-Type: ' + req.headers['content-type'] + '</p>' + '<p>Data:</p><pre>' + body + '</pre>'); }); } }).listen(3000);
client.js
require('http').request({ host: '127.0.0.1', port: 3000, url: '/', method: 'GET' }, function (res) { var body = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { body += chunk; }); res.on('end', function () { console.log('\n We got: \033[96m' + body + '\033[39m\n'); }); }).end();
server.js
require('http').createServer(function (req, res) { res.writeHead(200); res.end('Hello World'); }).listen(3000);
server.js
var qs = require('querystring'); require('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('\n got name \033[90m' + qs.parse(body).name + '\033[39m\n'); }); }).listen(3000);
client.js
var http = require('http') , 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('\n \033[90m✔ request complete!\033[39m'); process.stdout.write('\n your name: '); }); }).end(qs.stringify({ name: theName })); } process.stdout.write('\n your name: '); process.stdin.resume(); process.stdin.setEncoding('utf-8'); process.stdin.on('data', function (name) { send(name.replace('\n', '')); });