在使用Koa
写服务,发现自己一直使用的都是Express
之类的框架,却不知道NodeJS原生的Http API使用方法,遂查阅了文档,在此处记一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #!/usr/bin/env node const url = require('url'); const http = require('http'); const querystring = require('querystring');
const server = http.createServer((request, response) => { try { if(request.method === "GET") { response.writeHead(200, { 'Content-Type': 'text/html' }); let { query } = url.parse(request.url, true); response.write(`hello ${ query.name || 'world' }!`); } else if(request.method == "POST") { response.writeHead(405, { 'Content-Type': 'text/html' }); response.write(`Method Not Allowed!`); } } catch (err) { response.writeHead(500, { 'Content-Type': 'text/json' }); response.write(JSON.stringify(err)); } finally { response.end(); } }); server.listen(3000);
|