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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章