nodejs-http笔记

创建于2016 应该是当时看到别人的文章之后的笔记,如果作者看到请联系我

http事务解剖

创建服务

var http = require('http');
var server = http.createServer(function(request, response) {// magic happens here!});

还可以有另一种写法

var server = http.createServer();
server.on('request', function(request, response) {// the same kind of magic happens here!});

在一般的案例中,我们通过端口号监听服务

Method,url和Headers

var method = request.method;var url = request.url;

method 是http的提交方式,url是除去ip和端口的全链接

var headers = request.headers;var userAgent = headers['user-agent'];

headers 获取浏览器传递过来的所有header内容

RequestBody

var body = [];
request.on('data', function(chunk) {
  body.push(chunk);}).on('end', function() {
  body = Buffer.concat(body).toString();// at this point, `body` has the entire request body stored in it as a string});

处理错误请求

request.on('error', function(err) {// This prints the error message and stack trace to `stderr`.
  console.error(err.stack);});

整合上述

var http = require('http');

http.createServer(function(request, response) {var headers = request.headers;var method = request.method;var url = request.url;var body = [];
  request.on('error', function(err) {
    console.error(err);}).on('data', function(chunk) {
    body.push(chunk);}).on('end', function() {
    body = Buffer.concat(body).toString();// At this point, we have the headers, method, url and body, and can now// do whatever we need to in order to respond to this request.});}).listen(8080); // Activates this server, listening on port 8080.

现在我们还缺少对浏览器的反馈

http status code

response.statusCode = 404; // Tell the client that the resource wasn't found.

404错误 找不到页面,其他code也这么使用

设置回应的标题头

response.setHeader('Content-Type', 'application/json');
response.setHeader('X-Powered-By', 'bacon');

显示的发送头数据

response.writeHead(200, {'Content-Type': 'application/json','X-Powered-By': 'bacon'});

response body

response.write('');
response.write('');
response.write('

Hello, World!

'); response.write(''); response.write(''); response.end();

也可以这么发送

response.end('

Hello, World!

');

另一种错误处理的便捷方式

response.on('error',function(err){//...})

整合在一起

ar http = require('http');

http.createServer(function(request, response) {var headers = request.headers;var method = request.method;var url = request.url;var body = [];
  request.on('error', function(err) {
    console.error(err);}).on('data', function(chunk) {
    body.push(chunk);}).on('end', function() {
    body = Buffer.concat(body).toString();// BEGINNING OF NEW STUFF

    response.on('error', function(err) {
      console.error(err);});

    response.statusCode = 200;
    response.setHeader('Content-Type', 'application/json');// Note: the 2 lines above could be replaced with this next one:// response.writeHead(200, {'Content-Type': 'application/json'})var responseBody = {
      headers: headers,
      method: method,
      url: url,
      body: body
    };

    response.write(JSON.stringify(responseBody));
    response.end();// Note: the 2 lines above could be replaced with this next one:// response.end(JSON.stringify(responseBody))// END OF NEW STUFF});}).listen(8080);

简单的回应服务

var http = require('http');

http.createServer(function(request, response) {var body = [];
  request.on('data', function(chunk) {
    body.push(chunk);}).on('end', function() {
    body = Buffer.concat(body).toString();
    response.end(body);});}).listen(8080);

现在假设一个情况:

  • get请求
  • /echo 连接
  • 其他情况都返回404
var http = require('http');

http.createServer(function(request, response) {if (request.method === 'GET' && request.url === '/echo') {var body = [];
    request.on('data', function(chunk) {
      body.push(chunk);}).on('end', function() {
      body = Buffer.concat(body).toString();
      response.end(body);})} else {
    response.statusCode = 404;
    response.end();}}).listen(8080);

不要忘记,request是readStream response是writeStream,我们可以使用pipe简化上面的代码

var http = require('http');
http.createServer(function(request, response) {if (request.method === 'GET' && request.url === '/echo') {
    request.pipe(response);} else {
    response.statusCode = 404;
    response.end();}}).listen(8080);

增加处理错误请求的方法

var http = require('http');

http.createServer(function(request, response) {
  request.on('error', function(err) {
    console.error(err);
    response.statusCode = 400;
    response.end();});
  response.on('error', function(err) {
    console.error(err);});if (request.method === 'GET' && request.url === '/echo') {
    request.pipe(response);} else {
    response.statusCode = 404;
    response.end();}}).listen(8080);

你可能感兴趣的:(nodejs-http笔记)