nodejs的get與post
阿新 • • 發佈:2019-01-05
index.html
<html> <body> <form action="/api/v1/records" method="post"> name: <input type="text" name="name"> age: <input type="text" name="age" > <input type="submit" value="submit"> </form> </body> </html>
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);
server.js
var http = require('http'); var fs = require('fs'); var url = require('url'); var querystring = require('querystring'); function startServer (route,handle) { var onRequest = function(request, response) { //解析取得?之前的路由 var pathname = url.parse(request.url).pathname;var data = []; request.on('error', function (err) { console.error(err); }).on('data', function(chunk) { data.push(chunk); }).on('end', function() { if (request.method === 'post') { //當post的資料過大時,選擇主動銷燬 if (data.length > 1e6) { request.connection.destroy(); } data = Buffer.concat(data).toString(); route(handle, pathname, response, querystring.parse(data)); } else { //解析取得?之後的路由 true返回一個json //此方法只能取到get的值,post方法無法取值 var params = url.parse(request.url, true).query; route(handle, pathname, response, params); } }); } var server = http.createServer(onRequest); server.listen(3000); } console.log('finished'); module.exports.startServer = startServer;
router.js
var fs = require('fs'); function route(handle, pathname, response, params) { console.log('Routing a request for' + pathname); if (typeof handle[pathname] === 'function') { handle[pathname](response, params); } else { response.writeHead(200, {'Content-Type': 'text/html'}); fs.createReadStream(__dirname + '/404.html', 'utf8').pipe(response); } } module.exports.route = route;
handler.js
var fs = require('fs'); function home(response) { response.writeHead(200, { 'Content-Type': 'text/html'}); fs.createReadStream(__dirname + '/index.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, params) { response.writeHead(200, { 'Content-Type': 'application/json' }); response.end(JSON.stringify(params)); } module.exports = { home: home, review: review, api_records: api_records }