Get Programming with Node.js 学习笔记(2):处理 incoming 数据

lesson5. Handling incoming data

本章内容:

  • Collecting and processing request data
  • Submitting a POST request
  • Building a web application with basic routes

service 重做

const http = require('http');
const app = http.createServer();
function getJSONString (obj) {
  return JSON.stringify(obj, null, 2);
}
app.on('request', (request, response) => {
  console.info(`method: ${getJSONString(request.method)}`);
  console.info(`url: ${getJSONString(request.url)}`);
  console.info(`headers: ${getJSONString(request.headers)}`);
  response.writeHead(200, {
    'content-type': 'text/html'
  });
  let responseMessage = `<h1>this will show on the screen</h1>`;
  response.end(responseMessage)
});
app.listen(3000);
console.info('http://localhost:3000');

获取post请求的数据

const http = require('http');
const app = http.createServer();

function getJSONString (obj) {
  return JSON.stringify(obj);
}

app.on('request', (req, res) => {
  let body = [];

  req.on('data', (bodyData) => {
    body.push(bodyData);
  });

  req.on('end', () => {
    body = Buffer.concat(body).toString();
    console.info(`request body contents: ${body}`);
  });

  console.info(`method: ${getJSONString(req.method)}`);
  console.info(`url: ${getJSONString(req.url)}`);
  console.info(`headers: ${getJSONString(req.headers)}`);

  res.writeHead(200, {
    'content-type': 'text/html'
  });

  let responseMessage = '<h1>this will show on the screen</h1>';

  res.end(responseMessage);
});

console.info('open on http://localhost:3000');
app.listen(3000);

增加路由

const http = require('http');
const app = http.createServer();
const routerResponseMap = {
  '/info': '<h1>info page</h1>',
  '/about': '<h1>about page</h1>',
  '/error': '<h1>error page</h1>'
};

app.on('request', (req, res) => {
  res.writeHead(200, {
    'content-type': 'text/html'
  });
  if (routerResponseMap[req.url]) {
    setTimeout(function () {  // 模拟处理请求时间
      res.end(routerResponseMap[req.url])
    }, 1000);
  } else {
    res.end('<h1>welcome!</h1>');
  }
});

console.info('http://localhost:3000');

app.listen(3000);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值