TIL28: Node Sever

Charlie·2020년 12월 7일
0

Immersive Course TIL

목록 보기
28/39
post-thumbnail

Create Node Server

const http = require('http');
const server = http.createServer();
server.on('request', (request, response) => {
  // Do something
}).listen(8080);

또는

const http = require('http');
http.createServer((request, response) => {
  // Do something
}).listen(8080);

Node Server Example

const http = require('http');
const server = http.createServer((request, response) => {
  /* Error check for request */
  request.on('error', (err) => {
    console.error(err);
    response.statusCode = 400;
    response.end();
  });
  /* Error check for response */
  response.on('error', (err) => {
    console.error(err);
  });
  /* Handle request body */
  let body = [];
  request.on('data', (chunk) => {
    body.push(chunk);
  });
  const { method, url } = request;
  if (method === 'OPTIONS') {
    /* Set status code and header */
    response.statusCode = 200;
    response.setHeader(defaultCorsHeader);
    /* Or the 2 lines above could be replaced with this below one line */
    // response.writeHead(200, defaultCorsHeader);
  } else if (method === 'POST' && url === '/echo') {
    request.on('end', () => {
      /* Handle request body's data */
      body = JSON.parse(Buffer.concat(body).toString());
      /* Set header and status code */
      const header = defaultCorsHeader;
      header['Content-Type'] = 'application/json';
      response.writeHead(201, header);
      response.write(JSON.stringify(body));
      response.end();
      /* Or the 2 lines above could be replaced with this below one line */
      // response.end(JSON.stringify(responseBody));
    });
  } else {
    /* Handle else case */
    res.statusCode = 404;
    res.end();
  }
});
const PORT = 8080;
const ip = 'localhost';
server.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});
/* Default cors header */
const defaultCorsHeader = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Accept',
  'Access-Control-Max-Age': 10
};

코드 및 자료 출처: nodejs.org, 코드스테이츠(CodeStates)

0개의 댓글